我已经配置了动态模态,但单击模态之外的关闭不起作用,因为输入 id 和 for 属性是从父组件绑定的。
@Component({
selector: 'app-modal',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
template: `
<input
type="checkbox"
[id]="id()"
class="modal-toggle"
[checked]="open()"
/>
<div class="modal" role="dialog">
<div class="modal-box">
<ng-content></ng-content>
</div>
<label class="modal-backdrop" [attr.for]="id()">Close</label>
</div>
`,
styles: ``,
})
export class ModalComponent {
id = input<string>('appmodal');
open = input<boolean>(false);
}
问题在于,通过命名组件的输入
id
,会与原生 id
属性发生名称冲突。因此,DOM 中存在两个具有相同 ID 的元素,一次位于 app-modal
元素上,一次位于复选框上。因为模态元素是 DOM 中的第一个元素,所以它具有优先级。因此,关闭机构停止工作。只需将输入重命名为 id
以外的其他名称即可。