获取打字稿文件中指令的输入值
Get the input value of a directive inside the typescript file
我传递给指令的输入在 html 文件中正确显示,但我没有在 typescript 文件中获取它的值。如何在打字稿文件中访问它?
这是一个例子:
我有一个指令,在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
我有:
{{location}}
我在另一个 html user.html
文件中使用这个指令:
<test-info [location]='location'> </test-info>
位置在 user.html
中正确显示,但 .ts 文件中的 console.log 命令打印空值。
编辑:
在 user.ts
中,位置是在 Ajax 调用中分配的。这很可能就是构造函数或 ngOnInit() 缺少此值的原因。但是更新后怎么获取呢?
尝试使用 ngOnChanges
钩子。如果您真的更改了正确的值,那么您应该在那个钩子中获取它。
ngOnChanges() {
console.log('this.location: ' + this.location );
}
另一种方法是在 *ngIf
:
中包装组件
<test-info *ngIf="location" [location]='location'> </test-info>
我传递给指令的输入在 html 文件中正确显示,但我没有在 typescript 文件中获取它的值。如何在打字稿文件中访问它?
这是一个例子:
我有一个指令,在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
我有:
{{location}}
我在另一个 html user.html
文件中使用这个指令:
<test-info [location]='location'> </test-info>
位置在 user.html
中正确显示,但 .ts 文件中的 console.log 命令打印空值。
编辑:
在 user.ts
中,位置是在 Ajax 调用中分配的。这很可能就是构造函数或 ngOnInit() 缺少此值的原因。但是更新后怎么获取呢?
尝试使用 ngOnChanges
钩子。如果您真的更改了正确的值,那么您应该在那个钩子中获取它。
ngOnChanges() {
console.log('this.location: ' + this.location );
}
另一种方法是在 *ngIf
:
<test-info *ngIf="location" [location]='location'> </test-info>