不使用“set”就无法访问Angular Input变量

问题描述 投票:0回答:1

我是Angular的新手我无法理解这里发生的事情。我有两个组件,A和B,我希望将一些数据从A传递给B.在组件A中我有如下代码:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'comp-a',
  template: `<comp-b [var_x]="var_x"></comp-b>`
})
export class ParentComponent {
  // Info to send to Component B
  var_x: any = 'something'
}

然后在组件B中,我有类似的东西:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'comp-b',
  template: `Info from Component A: {{var_x}}`
})
export class ChildComponent {
  @Input() var_x: any;
}

问题是,该代码不起作用。我无法看到var_x的价值。我得到undefined。但是,当我用$Input()替换下面的代码时,我可以得到var_x的值。

var_x: any;

@Input() set var_x(_var_x: any) {
    this.var_x = _var_x;
}

我已经摸不着头脑为什么会这样。我的所有进口似乎都很好。我不能为我的生活弄清楚什么是错的,我希望那里的人可以帮助我。多谢你们!

angular angular6
1个回答
0
投票

角度CLI中的错误是什么,你的组件选择器必须在单引号内,例如:selector:'comp-b',你拥有的是选择器:comp-b'

© www.soinside.com 2019 - 2024. All rights reserved.