[英]No change detection on emit (Angular 2)
I am trying to get some values to change when I execute an emit from a directive; 当我从指令执行emit时,我试图获得一些值来改变;
Simplified version: 简化版:
HTML: HTML:
<div testDirective (onTouch)='test()'>
<p>{{test_value}}</p>
<a (click)='test()'>get data</a>
</div>
TypeScript: 打字稿:
private test_value: string = '';
test() {
this.test_value='TEST';
alert('Value: ' + this.test_value);
}
Directive: 指示:
@Directive({
selector: '[testDirective]',
host: {
'(document:touchend)': 'touchEnd($event)'
}
})
export class TestDirective {
@Output() onTouch: EventEmitter<any> = new EventEmitter();
touchEnd(e) {
this.onTouch.emit(null);
}
}
When I press the 'get data' link, I get the data + an alert 'Value: TEST' When I emit the onTouch, I get no data + an alert 'Value: TEST' 当我按下“获取数据”链接时,我得到数据+警告'值:TEST'当我发出onTouch时,我没有数据+警报'值:TEST'
Anyone who knows what the difference between these two methods is and why Angular does not detect this change in value when emitting, but does when clicking? 任何知道这两种方法之间区别的人是什么,以及为什么Angular在发射时没有检测到这种值的变化,但在点击时是什么?
I think @Output is only between parent and child. 我认为@Output仅在父母和孩子之间。 You can use a subject to communicate between directive and its host.
您可以使用主题在指令与其主机之间进行通信。
@Directive({
selector: '[myDir]'
})
export class MyDir {
@Input() myDir;
@HostListener('click', ['$event.target']) onClick() {
this.myDir.next(true);
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>isClicked: {{obs | async}}</h2>
<div [myDir]="subject">Click me</div>
</div>
`,
})
export class App {
subject = new BehaviorSubject(false);
obs = this.subject.asObservable();
constructor() {
}
}
通过在我的更改中添加zone.run解决了这个问题:
zone.run(() => this.test_value = 'TEST');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.