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

Angular change detection on input decorated property

如果我用 @Input 装饰器装饰我的 属性 并通过一些休息服务更新它,模板中插入的字符串 属性 每次更改时都会更新吗?

在组件中:

@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;
}

你可以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):

@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) { }
}