簡體   English   中英

Angular 對輸入修飾屬性的變化檢測

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM