Angular5 - html 和组件中的相同变量不同

Angular5 - Same variable in html and in component is different

我在 angular5 中遇到向导问题。 我有一个组件 parent,它在 child 组件中发送数据绑定,但绑定的数据在 child html 中显示良好,但在 child 组件中却没有.

Parent 组件

@Component({
  selector: 'app-element',
  templateUrl: '../templates/app.element.component.html',
})
export class AppElementComponent implements OnInit {

  titles: {} = {};

  constructor() {}

  ngOnInit(): void {
    // Details
    this.restService.postDb('url')
      .subscribe(response => {
         this.titles = response.title;
         // this.titles = { 'menu1': 'something', 'menu2': 'somethingelse'}
      });
  }

}

Parent 模板

  <div>
    <app-panel [titles]="titles"></app-panel>
  </div>

Child 组件

@Component({
  selector: 'app-panel',
  templateUrl: '../templates/app.panel.component.html',
})
export class AppPanelComponent implements OnInit {

  @Input() titles;

  constructor() {}

  ngOnInit() {
    //I put a timeout just to wait the binding
    setTimeout(function() {
      console.log(typeof this.titles);
      console.log(this.titles);
      }, 5000);
  }

}

Child 模板

<pre>{{ titles | json}}</pre>
<pre>{{ titles.keys | json}}</pre>

在 child 模板中,我有第一个预置标题数据,但第二个预置不起作用。并且在 child 组件中,两个控制台日志 return 未定义。我不明白为什么相同变量的值在模板和组件中不同。

谢谢。

在您的第一个 pre 中,您正在访问整个 object,但在第二个 pre 中,您试图访问一个 属性,在您的标题 object 中称为键,但是这属性不存在(它只有两个属性,名为 'menu1' 和 'menu2')。

如果您想访问 object 的密钥:

Object.keys(titles)

在您下面的代码中,this 指的是匿名函数,而不是 class。

ngOnInit() {
    //I put a timeout just to wait the binding
    setTimeout(function () {
        console.log(typeof this.titles);
        console.log(this.titles);
    }, 5000);
}

使用箭头代替函数来保持引用如下:

ngOnInit() {
    //I put a timeout just to wait the binding
    setTimeout(() =>  {
        console.log(typeof this.titles);
        console.log(this.titles);
    }, 5000);
}

顺便说一句,为了避免使用setTimeout,您可以使用原生Angular方法ngOnChanges。每当输入更改时都会调用它(请参阅 https://angular.io/guide/lifecycle-hooks)。


代码 titles.keys 正在尝试访问属性 keys 的值,但您的对象中没有属性 keys

如果你想得到你的对象的键数组,做这样的事情Object.keys(this.titles)你会得到数组['menu1', 'menu2'].

注意,如果要在模板中使用Object.keys,必须预先绑定如下:

@Component({
  selector: 'app-panel',
  template: `
    <pre>{{Object.keys(titles) | json}}</pre>
  `
})
export class AppPanelComponent implements OnInit {
  @Input() titles;
  Object = Object;
}