加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 ngrx / store:单向绑定到

发布时间:2020-12-17 17:07:59 所属栏目:安全 来源:网络整理
导读:在 input上通过[ngModel]使用单向绑定时,在输入中键入字符始终会将字符添加到 input的值中.问题是如果[ngModel]表达式继续返回其现有值,则 input价值没有刷新. 这是一个简单的例子: @Component({ selector: 'my-component',template: ` input type="text" [
在< input>上通过[ngModel]使用单向绑定时,在输入中键入字符始终会将字符添加到< input>的值中.问题是如果[ngModel]表达式继续返回其现有值,则< input>价值没有刷新.

这是一个简单的例子:

@Component({
  selector: 'my-component',template: `
    <input type="text" [ngModel]="foo.bar" />
  `
})
export class MyComponent {
  private foo = {
    bar: 'baz'
  };
}

我希望无论用户输入如何,输入总是显示“baz”,但事实并非如此.

我正在寻找这种行为的原因是ngrx / store / redux应用程序,其中< input>的值应由单向流动的状态确定.我创建了一个example use case on Plunker,其中Misko Hevery的描述不应该是可编辑的.该模型确实没有改变,但<输入>显示用户输入的内容.

在“No trackBy”部分,它可以正常工作,但只是因为Angular正在重绘所有强制重新评估的DOM元素(但这不是解决方案).将禁用或只读属性添加到< input>对我来说这不是一个可接受的答案,因为组件应该不知道不允许对此字段进行更改的潜在复杂状态逻辑.

我在React Redux中看到过这种行为,我想知道如果我们无法阻止用户改变他们自己的视图,我们如何在Angular 2中使用单向绑定.

解决方法

因为当从状态返回的值相同时不会触发ChangeDetection,所以唯一直接的方法是通过绑定到组件构造函数中商店的customer.descriptionLocked属性的customerDescriptionLocked属性集.我知道你不希望组件只使用readonly,因为你不希望组件知道状态确定锁的逻辑.通过绑定到customerDescriptionLocked属性,组件仍然不知道状态的设置逻辑.

<input type="text" placeholder="Description" [ngModel]="record.customerDescription" 
[readonly]="record.customerDescriptionLocked" (ngModelChange)="updateDescription(record,$event)" />

组件构造函数:

constructor(public store: Store<AppState>,private ref: ChangeDetectorRef){
  this.customerState = store.select('customer');
  this.customerState.subscribe((customerState:CustomerState) => {
    this.dashboardRecords = customerState.customers.map((customer:Customer):DashboardRecord => {
      return {
        customerId: customer.id,customerName: `${customer.personalInfo.firstName} ${customer.personalInfo.lastName}`,customerDescription: customer.description,customerDescriptionLocked: customer.descriptionLocked,customerUpdateCount: customer.updated
      };
    })
  });
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读