簡單地說,我想兩路我的開關組件使用ngModel與自定義組件
像這樣綁定到一個布爾值,在服務:
@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
事件應該觸發,反之亦然。
對於雙向綁定,您需要使用EventEmitter公開一個stateChange輸出事件。 – pixelbits
你可以發佈這個作爲一個示例代碼的答案嗎? –