input.required<boolean>()
->;表示单向绑定,但您使用的是双向绑定,因此该函数被替换为boolean
的值
要解决这个问题,我们可以在HTML中使用单向绑定
<input type="checkbox" [ngModel]="isSelection2" />
当我使用作为子级提供的代码并提供来自父级的输入时,当我try 使用[(ngModel)]="isSelection2"
时,ANGLE只是抛出一个错误
model.required<boolean>()
->;的意思是双向绑定,所以您的示例工作得很好,因为它做的正是它应该做的事情!
请使用以下代码/stackblitz作为您的参考!
子元素
import { Component, input, model } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-子元素',
standalone: true,
imports: [FormsModule],
template: `
<input type="checkbox" [(ngModel)]="isSelection" />
<pre>{{ isSelection() }}</pre>
<p>{{ getTypeof(isSelection) }}</p>
<hr />
<input type="checkbox" [ngModel]="isSelection2" />
<pre>{{ isSelection2() }}</pre>
<p>{{ getTypeof(isSelection2) }}</p>
`,
})
export class ChildComponent {
public isSelection = model.required<boolean>();
public isSelection2 = input.required<boolean>();
public getTypeof(value: any): string {
return typeof value;
}
}
双手
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { ChildComponent } from './app/子元素/子元素.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [ChildComponent],
template: `<app-子元素 [isSelection2]="true" [isSelection]="false"/>`,
})
export class App {}
bootstrapApplication(App);
Working Stackblitz