using async pipe to the property on template

拥有回忆 提交于 2021-02-16 14:37:08

问题


export class MyClass {
    data: MyData;  
    constructor(private dataService: DataService) {    
      this.dataService.getData().subscribe((myData) => {
        this.data = myData;
      });  
    }
}

data is successfully retrieved trough web service. MyData object has property firstName which I want to represent inside template using async pipe.

I tried with

<input required [ngModel]="data.firstName | async" (ngModelChange)="onChange($event)" name="firstName">

this approach doesn't bind property to the template at all, [(ngModel)]="data.firstName" works but I've been told that this approach cannot be used together with async pipe.

Update:

getData(): Observable<MyData>{
        return Observable.from([this.fakeData()]
            .map(res=>res as MyData));
    }

回答1:


Either use

export class MyClass {
    data: Promise;  
    constructor(private dataService: DataService) {    
      this.data = this.dataService.getData()
    }
}

The | async pipe is already the subscribing

with

<input required [ngModel]="(data | async)?.firstName" (ngModelChange)="onChange($event)" name="firstName">

or with your code

<input required [ngModel]="data?.firstName" (ngModelChange)="onChange($event)" name="firstName">

where I just added ? to avoid an error while the data is not yet available.



来源:https://stackoverflow.com/questions/47315210/using-async-pipe-to-the-property-on-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!