更改父级属性更改的最佳方法

时间:2017-11-09 17:03:43

标签: angular

我有这个结构:

$(document).ready(function () {
    $("input[name='tech']").change(function () {

        maxAllowed = 8;
        var count = 1;
        var first = $("input[name='tech']:checked:first").data("category");
        var cnt = $("input[name='tech']:checked").length;
        if (cnt > maxAllowed) {
            $(this).prop("checked", "");
            alert('You can select maximum ' + maxAllowed + ' categories!');
        }

        var cat = $("input[name='tech']:checked").each(function(index) {
            if($(this).data('category') != first)
            count ++;
            if(count > 2)
            alert("Can't have more than two categories");
        });  
    });
});

@Component({
 selector: "parent-component",
 template: `
 <div>
  <child-component *ngIf='isLogin'></child-component>
 </div>
  `,
})
export class ParentComponent {
  public isLogin = false;

  myFunction( ) {
    if (something) this.isLogin = true;
  }
}

我相信这是非常基本的东西。我只需要能够在@Component({ selector: "dropteam-header-user", template: ` <button (click)="trigger()">Click me</button> `, }) export class ChildComponent { trigger() { // change ParentComponent's isLogin property here } } 内更改ParentComponent属性。 ChildComponent也应该能够改变自己的财产。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以将输出添加到您的子组件,如下所示

export class ChildComponent {
  @Output() loginStatusChanged : EventEmitter<boolean> = new EventEmitter<boolean>();
  trigger() {
    this.loginStatusChanged.emit(true); // or false
  }
}

然后在父组件中附加到此事件

<dropteam-header-user (loginStatusChanged)="loginStatusChanged($event)"></dropteam-header-user>


export class ParentComponent {
  public isLogin = false;

  myFunction( ) {
    if (something) this.isLogin = true;
  }

  loginStatusChanged(val: boolean) {
    this.isLogin = val;
  }
}