我正在尝试编写一个可重用于我的应用程序中的组件,有时将显示控制按钮,有时则不会。
理想情况下,我希望从属性的存在或不存在中获取它,以便使用该组件看起来像<generic-component hideControls></generic-component>
,并在我的组件中基于该属性是否存在而设置布尔变量,但我无法找到一种方法来实现这一点。
有什么办法可以做到这一点吗?
我尝试了以下稍微复杂一点的版本(虽然理想情况下我不需要在showControls / hideControls上设置值);
generic.component.html
<div>
<div>Stuff</div>
<div *ngIf="showControls">Controls</div>
</div>
通用组件.generic.component.ts
// imports etc.
@Component({
selector: 'generic-selector',
templateUrl: 'generic.component.html'
})
export class GenericComponent implements OnInit {
@Input()
public showControls: boolean = true;
// other inputs and logic
}
这种方式失败了,因为使用<generic-selector showControls="false"></generic-selector>
将showControls设置为字符串"false",它是真值,而不是布尔值。因此,我必须在组件中添加大量混乱的代码来获取输入并根据是否提供字符串"false"来将其转换为布尔值。希望有一种更简洁的方法来解决这个问题,但我更喜欢上面提到的另一种选项。
false
是 JavaScript 中的保留关键字,不能用作变量名。 - andii1997