离子切换组件之间的2路绑定

时间:2017-08-24 13:53:03

标签: angular ionic-framework ionic2 ionic3

我正在我的应用中构建设置,而我们的“设置”页面有多个设置类别。为了对此进行管理,我的“设置”页面流程如下:SettingsPage <uses> ProfileSettingsComponent <uses> SettingsComponent[]。我遇到了孩子和孙子组件的问题。

我正在尝试将一个设置对象传递到SettingsComponent并将其绑定回父级。现在,如果我传入了setting属性,我所得到的只是值,而不是属性的名称,属性也不会在父级上更新。

我们来看一些代码......

ProfileSettingsComponent

import { Component, OnInit } from "@angular/core";
import { SettingsService } from "../../services/settings.service";
import { SettingsKeys } from "../../constants/settings.constants";

@Component({
    selector: "profile-settings",
    template: "profile-settings.component.html",
})
export class ProfileSettingsComponent implements OnInit {

    public settings: ProfileSettings;

    constructor(private _settings: SettingsService) { }

    public ngOnInit() {
         this.settings = new ProfileSettings(settings[SettingsKeys.Profile] || {})) // returns {email:false, name:false}, etc.
            .then(() => console.log(this.profile, this.settings));
    }

    public updateSettings(e) {
        console.log('Settings.Profile', this.settings); // Eventually persist this back to settings once this.settings actually updates from the child component
    }

profile-settings.component.html

<div class="profile-settings" padding>
    <ion-list *ngIf="settings">
        <setting label="Email" [(setting)]="settings.email" (toggled)="updateSettings($event)"></setting>
    </ion-list>
</div>

setting.component.ts

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
    selector: "setting",
    templateUrl: "setting.component.html"
})
export class SettingComponent {

    @Input() public label: string;
    @Input() public setting: any;
    @Output() public toggled: EventEmitter<any> = new EventEmitter<any>();

    constructor() { }

    public toggle(e) {
        this.toggled.emit(this.setting);
    }

}

setting.component.html

<ion-item>
    <ion-label>
        <h2>{{label}}</h2>
    </ion-label>
    <ion-toggle [(ngModel)]="setting" (ngModelChange)="toggle($event)"></ion-toggle>
</ion-item>

在Angular 1中做的最简单的事情 - 更新注入子组件的父属性 - 非常困难。有没有人有正确的方向让我遵循以实现我想要的目标?

1 个答案:

答案 0 :(得分:2)

如果我正确阅读了您的代码,那么您将settings.email传递给您的子组件truefalse。使ngModel在您的子组件中工作是正确的,但是在ngModelChange上,您只是将this.setting传递回父组件,而父组件又可以是truefalse所以您的行为是正确的描述是预期的。

如果您想知道更改了哪个设置,则需要将更多信息传递给您的子组件,例如:

{ id: 1, email: false }

在您的子组件中,您可以在ngOnInit中初始化您的ngModel,如下所示:

this.myNgModel = setting.email

在您的toggle方法中,您可以执行以下操作:

this.toggle.emit({ id: setting.id, email: this.myNgModel });
相关问题