带有选择器的 ng-content 中的条件重复模板引用

Far*_*tab 1 angular-template angular ng-content

我有一个组件,它根据客户端设备大小切换组件的模板。组件代码为:

import {Component} from '@angular/core';
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';

@Component({
    selector: 'ui-switcher',
    template: `
        <ng-content *ngIf="isSmall" select="mobile"></ng-content>
        <ng-content *ngIf="!isSmall" select="web"></ng-content>
`
})
export class UiSwitcherComponent {
    public isSmall: boolean;

    constructor(breakpointObserver: BreakpointObserver) {
        breakpointObserver.observe([Breakpoints.Small, Breakpoints.XSmall]).subscribe(result => {
            this.isSmall = result.matches;
        });
    }    
}
Run Code Online (Sandbox Code Playgroud)

我像这样使用它:

<ui-switcher>
    <web>
        <!-- some commented details -->
        <input class="form-control mr-2" #searchInput 
        type="text" (keyup)="this.search(searchInput.value)">
    </web>

    <mobile>
        <!-- some commented details -->
        <input class="form-control" #searchInput 
        type="text" (keyup)="this.search(searchInput.value)">
    </mobile>
</ui-switcher>
Run Code Online (Sandbox Code Playgroud)

在移动尺寸中,一切正常,但在桌面尺寸中,传递给search(value)函数的值始终为空字符串。

当我调试应用程序时,似乎#searchInputtemplateref 工作不正常(它引用的元素的值始终为空)。

为什么模板引用不能正常工作?

yur*_*zui 6

在角度模板中,每个视图的引用变量应该是唯一的。

视图可以是两种类型ViewEmbeddedView。我们在结构指令(在ng-template标签或 内*ngFor)中编写的模板表示嵌入的视图。这样我们就可以在不同的 ng-templates 中拥有相同名称的模板引用变量。

有关示例,请参见

让我们想象一下我们AppComponent在模板中写了:

<ui-switcher>
    <web>
        <!-- some commented details -->
        <input class="form-control mr-2" #searchInput 
        type="text" (keyup)="this.search(searchInput.value)">
    </web>

    <mobile>
        <!-- some commented details -->
        <input class="form-control" #searchInput 
        type="text" (keyup)="this.search(searchInput.value)">
    </mobile>
</ui-switcher>
Run Code Online (Sandbox Code Playgroud)

Angular 将其视为一个 AppComponentView,因为此模板中没有任何结构指令。两个输入都属于同一个视图。

现在,当 Angular 编译器解析这个模板时,它会每个视图创建一个具有refNodeIndices属性的ViewBuilder

private refNodeIndices: {[refName: string]: number} = Object.create(null);
Run Code Online (Sandbox Code Playgroud)

保存当前模板中的所有引用。

让我们重现您的案例: 在此处输入图片说明

我们可以看到第二个模板引用变量覆盖了之前的。

结果 Angular 在同一个元素上处理 click 事件:

在此处输入图片说明