TS 类中的角度数据绑定



在我的组件中,我指定了一个绑定在 UI 上的属性。

元件

export class MyComponent implements OnInit {
public propertyA:string;
public propertyB:string;
}

用户界面

<textarea matInput rows="10" 
placeholder="Body" [(ngModel)]="formData.propertyA" 
[ngModelOptions]="{standalone: true}"></textarea>

我该怎么做这样的事情:

export class MyComponent implements OnInit {
public propertyA:string = "Some text with {{propertyB}} bound.";
public propertyB:string;
}

所以基本上,我将属性 A 绑定到文本框中,嵌套在属性 A 中的是属性 B 的值,它根据另一个数据绑定进行更新?

export class MyComponent implements OnInit {
public propertyA:string = `Some text with ${this.propertyB} bound.`;
public propertyB:string;

}

你可以试试这个模板文字

如果我们需要propertyApropertyB保持同步,而不仅仅是最初计算它:

我 格特斯

最简单的方法是getters.请记住,在模板中使用getter/functions将在每个更改检测周期执行它(使此可执行文件尽可能简单(。

export class MyComponent implements OnInit {
public get propertyA():string {
`Some text with ${this.propertyB} bound.`;
};
public propertyB:string;
}

二 可观测

更好的方法是将 Observable 用于可随时间变化的值。

export class MyComponent implements OnInit {
public propertyA = this.propertyB.pipe(
map(propertyB => `Some text with ${propertyB} bound.`),
);
// BehaviorSubject is Subject that have initial value and repeat the last value
public propertyB: Observable<string> = new BehaviorSubject('');
// somewhere
foo(){
this.propertyB.next('New value');
}
}
// template
<div>propertyA: {{propertyA | async}}</div>
<div>propertyB: {{propertyB | async}}</div>

最新更新