[英]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.