[英]Angular change detection on input decorated property
如果我用 @Input 裝飾器裝飾我的屬性並通過一些 rest 服務更新它,模板中的字符串插值屬性是否會在每次更改時更新?
在一個組件中:
@Input()
myProperty: string;
在模板中:
{{myProperty}}
您不能使用@Input
綁定來自服務 ( @Injectable
) 的值,因為@Input
專門用於通過父模板將值從父組件傳遞到子組件:
@Component({
selector: 'app-parent',
template: `<app-child [name]='name'></app-child>`
})
export class ParentComponent {
name: string = "World";
}
@Component({
selector: 'app-child',
template: `<p>Hello, {{name}}!</p>`
})
export class ChildComponent {
@Input() name: string;
}
您可以使用AsyncPipe
綁定到一個Observable
(這里我從BehaviorSubject
創建了一個Observable
,但它可以很容易地從通過HttpClient
發出 HTTP 請求的方法返回):
@Injectable({
providedIn: 'root'
})
export class NameService implements OnInit {
private name = new BehaviorSubject('');
public name$ = this.name.asObservable();
ngOnInit(): void {
this.name.next('World');
}
}
@Component({
selector: 'app-child',
template: `<p>Hello, {{nameService.name$ | async}}!</p>`
})
export class ChildComponent {
constructor(public nameService: NameService) { }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.