我传递给指令的输入在html文件中正确显示,但在typescript文件中没有得到其值。如何在typescript文件中访问它?
下面是一个示例:
test-info.ts 具体如下:
test-info.ts
@Component({ selector: 'test-info', templateUrl: 'test-info.html' }) export class TestInfo { @Input('location') location; constructor(...) { console.log('this.location: ' + this.location ); //------> Prints null }
test-info.html 我有:
test-info.html
{{location}}
我在另一个html中使用这个指令 user.html
user.html
<test-info [location]='location'> </test-info>
位置正确显示在 user.html ,但控制台。ts文件中的log命令打印空值。
编辑: user.ts
user.ts
尝试使用 ngOnChanges 钩如果你真的改变了正确的值,那么你应该把它放在钩子里。
ngOnChanges
ngOnChanges() { console.log('this.location: ' + this.location ); }
另一种方法是将组件包装在 *ngIf
*ngIf
<test-info *ngIf="location" [location]='location'> </test-info>