Angular 2+:输入修饰符不反映复选框

时间:2019-02-11 22:16:17

标签: html css angular checkbox angular2-forms

我有一个组件

timeBoxSelector HTML:

<input type="checkbox" [(ngModel)]="selected">

TS:

@Component({
   ...
})
export class TimeboxComponent implements OnInit {
    @Input() selected: boolean;

    constructor() {}

    ngOnInit() {
        console.log('Selected: ', this.selected);
    }
}

现在,当我创建

<app-timebox selected="false"><app-timebox/>
<app-timebox selected="true"><app-timebox/>

在两种情况下,该复选框最初都显示为选中状态。为什么会这样,我该如何解决?

1 个答案:

答案 0 :(得分:3)

在两种情况下,您都将绑定非空字符串,它们是truthy值。使用brackets表示法告诉Angular绑定值将作为Java表达式求值:

<app-timebox [selected]="false"><app-timebox/>
<app-timebox [selected]="true"><app-timebox/>