我在我的Angular应用程序中遇到了一个有趣的行为,我希望有人能解释一下它. 我有一个工作代码片段,我定义了一个名为isSelection的属性,如下所示:

public isSelection = model.required<boolean>();
public getTypeof(value: any): string {
    return typeof value;
}

IsSelection属性是使用Model.必需信号进行初始化的

<input type="checkbox" [(ngModel)]="isSelection" />
<p>{{ getTypeof(isSelection) }}</p>

我使用[(ngModel)]将isSelection属性绑定到复选框输入

段落显示类型isSelection. 在这种情况下,isSelect显示为一个函数,当我按下复选框时,isSelect的类型从未改变.

但是,当我将属性声明更改为:

public isSelection = input.required<boolean>();

行为发生了变化,isSelection的类型似乎从函数切换到了boolean.

注意,我使用的是angular 17.3.1的最新版本.

推荐答案

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

Typescript相关问答推荐

脉轮ui打字脚本强制执行图标按钮的咏叹调标签-如何关闭

如何在类型脚本中声明对象其键名称不同但类型相同?

在TypScript手册中可以视为接口类型是什么意思?

如何基于对象关键字派生类型?

使用FormArray在Angular中添加排序

如何创建泛型类型组件来使用React Native的FlatList或SectionList?'

如何用不同的键值初始化角react 形式

使Typescribe强制所有对象具有相同的 struct ,从两个选项

如何编写一个类型脚本函数,将一个对象映射(转换)为另一个对象并推断返回类型?

向NextAuth会话添加除名称、图像和ID之外的更多详细信息

如何使用WebStorm调试NextJS的TypeScrip服务器端代码?

如何在Type脚本中动态扩展函数的参数类型?

如何将对象数组中的键映射到另一种对象类型的键?

是否可以强制静态方法将同一类型的对象返回其自己的类?

将类型脚本函数返回类型提取到VSCode中的接口

任何导航器都未处理有效负载为";params";:{";roomId";:";...";}}的导航操作

基于闭包类型缩小泛型类型脚本函数的范围

为什么TS条件返回要求不明确的强制转换而不是精确的强制转换?

从泛型对象数组构造映射类型

解析错误:DeprecationError: 'originalKeywordKind' 自 v5.0.0 起已被弃用,无法再使用