使用模板变量从Angular指令发回数据



假设我有一堆指令,

@Directive({
selector: "[someDirective1]"
})
export class SomeDirective1 {}

@Directive({
selector: "[someDirective2]"
})
export class SomeDirective2 {
@Input() blah: String
...
}

假设我使用它如下:

@Component({
selector: 'blah-component'
template: `
<div someDirective1>
<div someDirective2>
</div>
</div>
`
})
export class BlahComponent {


}

现在我想把一个参数从someDirective1传递到someDirective2

通常的方法是在someDirective1上声明@Output,在BlahComponent中捕获该值,然后将其作为@Input再次传递

@Component({
selector: 'blah-component'
template: `
<div someDirective1 (somethingChanged)="changeSomething($event)">
<div someDirective2 [blah]="somethingThatChanged">
</div>
</div>
`
})
export class BlahComponent {

somethingThatChanged: string
function changeSomething(value) {
....
somethingThatChanged = ...
} 

}

有没有一种方法可以在没有输出功能温度可变输入锅炉板的情况下做到这一点?类似这样的东西(这不是有效的语法,正在寻找概念上可以这样工作的东西(:

@Component({
selector: 'blah-component'
template: `
<div someDirective1={ let someContext }>
<div someDirective2 [blah]="someContext.someValue">
</div>
</div>
`
})
export class BlahComponent {


}

问题与Angular 9、10、11 有关

在Directive decorator上使用exportAs属性,通过设置该属性,我们可以向模板公开指令实例,最后使用template变量,我们可以访问模板上任何位置的指令实例。

方向性1.ts

@Directive({
selector: "[someDirective1]",
exportAs: 'someDirective1'
})
export class SomeDirective1 {}

方向性2.ts

@Directive({
selector: "[someDirective2]",
exportAs: 'someDirective2'
})
export class SomeDirective2 {
@Input() blah: String
...
}

模板内部定义模板变量以访问指令实例

@Component({
selector: 'blah-component'
template: `
<div someDirective1 #d1="someDirective1">
<div someDirective2 [blah]="d1.someValue">
</div>
</div>
`
})
export class BlahComponent {}

最新更新