【发布时间】:2018-10-08 23:30:10
【问题描述】:
我有一个组件可以根据客户端设备大小切换组件的模板。组件代码为:
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;
});
}
}
我是这样使用的:
<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>
在移动设备大小中,一切正常,但在桌面大小中,传递给 search(value) 函数的值始终为空字符串。
当我调试应用程序时,#searchInput templateref 似乎无法正常工作(它所引用的元素的值始终为空)。
为什么 templateref 不能正常工作?
【问题讨论】:
-
我不相信你可以有两个具有相同模板引用名称的元素,角度模板编译器将始终采用第一个元素并忽略第二个
-
但现在似乎跳过了第一个,因为在移动设备中一切正常
-
我不知道它应该如何表现,这充其量是无证行为......
标签: angular angular-template ng-content