using async pipe to the property on template

Viewed 1859
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 Answers

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.

Related