简体   繁体   English

Angular 对输入修饰属性的变化检测

[英]Angular change detection on input decorated property

If I decorate my property with @Input decorator and update it via some rest service, will a string interpolated property in a template be updated every time it changes?如果我用 @Input 装饰器装饰我的属性并通过一些 rest 服务更新它,模板中的字符串插值属性是否会在每次更改时更新?

In a component:在一个组件中:

@Input()
myProperty: string;

In a template:在模板中:

{{myProperty}}

You cannot use @Input to bind a value from a service ( @Injectable ), as @Input is specifically for passing values from a parent component to a child component via the parent's template:您不能使用@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;
}

You could bind to an Observable using the AsyncPipe (here I've created an Observable from a BehaviorSubject , but it could just as easily be returned from a method that makes an HTTP request via HttpClient ):您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM