为什么这在Angular中不起作用?

时间:2018-08-11 13:54:46

标签: angular angular5 angular6

我有一个父组件和一个子组件。 我将方法从父组件传递到子组件。该子组件从父组件调用传递的方法,并将“ this”(子组件的实例)发送给父组件。 现在,如果我使用上面传递的实例更改子组件中的任何属性,它将不会检测到任何更改。

例如,

@Component({...})
export class Parent {
  toChild(obj) {
      obj.mssg = "changes"; //this should trigger change detection in child component 
  }
}

Template:
<div>
<child [toChange]="toChange"></child>
</div>

@Component({...})
export class Child {
    mssg:string = "";

    @Input() toChild:Function;

    handleOnClick(evt) {
       this.toChild(this);
    }
}

Template:
<div (click)="handleOnClick($event)">{{mssg}}</div>

3 个答案:

答案 0 :(得分:1)

您的语法不太正确,就像别人提到的那样...您的名称有些错误。

我能够使用您的技术但在纠正语法的情况下,在没有输出属性的情况下正常进行更改检测。

父组件代码

  toChild = obj =>
      obj.mssg = "changes"; //this should trigger change detection in child component 

这定义了一个作为函数的属性。

父模板

<hello [toChange]="toChild"></hello>

在这里,我将其绑定到拥有该功能的属性

子组件

  mssg: string = "click here";

  @Input() toChange: Function;

  handleOnClick(evt) {
    this.toChange(this);
  }

您可以在这里找到有效的堆叠闪电战:https://stackblitz.com/edit/angular-osqytg?file=src%2Fapp%2Fhello.component.ts

答案 1 :(得分:0)

如果要将值从子级传递给父级,则应使用 @output 事件发射器

 <child-comp  [parentCount]="count"  (change)="updateFromChild($event)"></child-comp>

及其子组件中,

export class ChildComponent implements OnInit {
 @Input("parentCount")
  count: number;

  @Output()
  change: EventEmitter<number> = new EventEmitter<number>();

  updateCount() {
    this.count++;
    this.change.emit(this.count);
  }
  constructor() { }

  ngOnInit() {
  }

}

DEMO

答案 2 :(得分:0)

实现此目标的最佳方法是使用输入和输出事件

@Component({...})
class Parent{
  mssg: string = '';
  updateChild(){
    this.mssg = "changes"; //this will trigger change detection in child component 
  }
}

<child [mssg]="mssg" (onClick)="updateChild()"></child> 

@Component({...})
class Child{
  @Input()
  mssg:string = "";

  @Output()
  onClick: EvenEmitter<void> = new EventEmitter<void>();

  handleOnClick(){
    this.onClick.next()
  }
}

试图通过将父函数作为参数传递给子函数来修改子函数,这是不可行的,因为组件作用域未正确绑定,这通常是一个坏主意,因为真是令人费解。

相关问题