gpt4 book ai didi

typescript - 将 ngModel 与自定义组件一起使用

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:54 24 4
gpt4 key购买 nike

简单地说,我想将我的 Switch 组件双向绑定(bind)到服务中的 bool 值

像这样:

@Component({
selector: 'my-switch',
template: '...'
})

export class Switch {
@Input() state: Boolean

toggle() {
if (this.state) {
this.state = false
} else {
this.state = true
}
}
}

@Injectable()

class export FooService {
theBoolean: Boolean
}

@Component({
selector: 'my-app',
template: '<my-switch [(state)]="_foo.theBoolean"></my-switch>{{ _foo.theBoolean }}'
})

export class App {
constructor(private _foo: FooService) {}
}

所以这里应该发生的是,当切换开关时,应该触发 FooService 中的 onChanges 事件,反之亦然。

最佳答案

要使双向绑定(bind)起作用,您需要声明一个名为“stateChange”的输出事件

@Output stateChange: EventEmitter<Boolean>=new EventEmitter();

然后在您的切换实现中:

toggle() {
if (this.state) {
this.state = false;
} else {
this.state = true
}
this.stateChange.emit(this.state);
}

在您的 HTML 模板中:

 [(state)]="model"

相当于:

 [state]="model"  (stateChange)="model=$event"

其中 $event 是传递给 EventEmitter 的 emit 方法的参数。每当状态发生变化时,它都会发出 stateChange 事件,然后更新父组件中的模型 - 从而使模型保持同步

关于typescript - 将 ngModel 与自定义组件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36972458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com