如果我用@Input 裝飾器裝飾我的屬性并通過一些休息服務更新它,模板中的字串插值屬性是否會在每次更改時更新?
在一個組件中:
@Input()
myProperty: string;
在模板中:
{{myProperty}}
uj5u.com熱心網友回復:
您不能用于@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;
}
您可以使用系結到 aObservableAsyncPipe(這里我Observable從 a 創建了一個BehaviorSubject,但它可以很容易地從通過 發出 HTTP 請求的方法回傳HttpClient):
@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) { }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/444775.html
標籤:有角度的 模板 输入 特性 angular2-changedetection
