Angular @input值未定义

前端之家收集整理的这篇文章主要介绍了Angular @input值未定义前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
将值从父级传递给子级.子组件中接收的值未定义 working example

这是我的app.component

import { Component,OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';

interface ItemsResponse {
  data: any[];
}
@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
    constructor(private http: HttpClient) {}
  ngOnInit() {
    this.getPosts();
    console.log( this.name); // name is undefined
  }
  name;
  results:Array<any> = []; // code changed
    getPosts() {
        this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res =>
        this.name = res); // code changed
    }
}

这是我的hello组件,其中数据被传递给子组件
正如您所看到的,在构造函数中未定义通过angular的@input装饰器从父组件传递到子组件的名称.

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

@Component({
  selector: 'hello',template: `<pre>{{name | json}}</pre>`,styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
}

并在Hello.component中

import { Component,template: `<h1>hi</h1><pre>{{name | json}}</pre>`,styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
   ngOnInit() {
    console.log('name',this.name); // name is undefined
  }
  @Input() name: string;
}

working example

解决方法

首先,您的代码是异步的,因此您的console.log需要在订阅中:

.subscribe(res => {
   this.name = res
   console.log(this.name);
})

请查看此信息以获取更多信息:How do I return the response from an Observable/http/async call in angular2?

其次,您希望将对象传递给您的孩子,而不是

<hello name="{{ name }}"></hello>

你想做的事:

<hello [name]="name"></hello>

DEMO

由于这是异步的,因此名称最初将是未定义的,因为响应需要一些时间.您可以在子项中使用OnChanges来跟踪值何时到达.只要@Input值发生变化,就会触发OnChanges.所以你可以有条件地检查价值是否在那里,当它出现时,做你需要做的任何事情.

ngOnChanges() {
  if(this.name) {
    console.log(this.name)
  }
}

https://stackblitz.com/edit/angular-rpc1vy?file=app/hello.component.ts

猜你在找的Angularjs相关文章