Angular 12个分量输入无值
Angular 12 component input without value
此 post 相关于:
我想用一个名为 scrollable
.
的 Boolean 输入属性实现一个卡片组件
<card>...</card>
没有可滚动属性导致控制器 false
<card [scrollable]>...</card>
只有可滚动属性结果为 true
我已经在链接 post 中尝试过可接受的解决方案。
Stackblitz: https://stackblitz.com/edit/angular-ivy-ylsxzm?file=src/app/app.component.html
更新
为了解决这个问题,我只需要从 Scrollable 属性中删除方括号。
分叉 Stackblitz:
https://stackblitz.com/edit/angular-ivy-s6d8ag?file=src/app/app.component.html
像这样更改您的card.component.ts
:
export class CardComponent {
constructor() {}
ngOnInit() {
if (!this._scrollable) this._scrollable = false;
console.log(this._scrollable);
}
public _scrollable: boolean;
@Input()
get scrollable() {
return this._scrollable;
}
set scrollable(value: any) {
this._scrollable = this.coerceBooleanProperty(value);
}
coerceBooleanProperty(value: any): boolean {
return value != null && `${value}` !== 'false';
}
}
现在,您可以像这样使用它:
<card></card> // _scrollable = false
<card scrollable></card> // _scrollable = true
请注意,您可以在不使用 []
的情况下使用 scrollable
,因为它是一个布尔值,并且默认为 true
。您也可以将它与 []
一起使用,但您必须传递将导致布尔值的表达式(或组件 属性)。
<card [scrollable] = "false"></card> // _scrollable = false
<card [scrollable] = "true"></card> // _scrollable = true
此 post 相关于:
我想用一个名为 scrollable
.
<card>...</card>
没有可滚动属性导致控制器false
<card [scrollable]>...</card>
只有可滚动属性结果为true
我已经在链接 post 中尝试过可接受的解决方案。
Stackblitz: https://stackblitz.com/edit/angular-ivy-ylsxzm?file=src/app/app.component.html
更新
为了解决这个问题,我只需要从 Scrollable 属性中删除方括号。
分叉 Stackblitz: https://stackblitz.com/edit/angular-ivy-s6d8ag?file=src/app/app.component.html
像这样更改您的card.component.ts
:
export class CardComponent {
constructor() {}
ngOnInit() {
if (!this._scrollable) this._scrollable = false;
console.log(this._scrollable);
}
public _scrollable: boolean;
@Input()
get scrollable() {
return this._scrollable;
}
set scrollable(value: any) {
this._scrollable = this.coerceBooleanProperty(value);
}
coerceBooleanProperty(value: any): boolean {
return value != null && `${value}` !== 'false';
}
}
现在,您可以像这样使用它:
<card></card> // _scrollable = false
<card scrollable></card> // _scrollable = true
请注意,您可以在不使用 []
的情况下使用 scrollable
,因为它是一个布尔值,并且默认为 true
。您也可以将它与 []
一起使用,但您必须传递将导致布尔值的表达式(或组件 属性)。
<card [scrollable] = "false"></card> // _scrollable = false
<card [scrollable] = "true"></card> // _scrollable = true