Passing data from Parent to Child via template

南笙酒味 提交于 2019-12-10 11:29:46

问题


I have a template user like following:

<div class="jumbotron">
  <div class="container">
    <h2><i class="fa fa-user"></i> {{username}}</h2>
    <p><i class="fa fa-star"></i> {{reputation}}</p>
  </div>
</div>
<app-list user={{username}}"></app-list>

My component for app-list looks like:

export class ListComponent implements OnInit {
  @Input() user: string;

  constructor() { }

  ngOnInit() {   
    console.log(this.user);
  }  

}

The username and reputation is correctly shown on the page. However the username value is not passed correctly to the sub component app-list as it only print out an empty string.

How can I pass the username to the app-list component?

Edit

The user component looks like:

export class UserComponent implements OnInit {

  private username: string;
  private reputation: number;

  constructor(private route: ActivatedRoute, private apiService: ApiService) {
  }

  ngOnInit() {
    this.route.params.subscribe((params: Params) => (
      this.apiService.getUser(params['username']).subscribe((response: Response) => {
          console.log(response.json());
          this.username = response.json().username;
          this.reputation = response.json().reputation;
        }, (error) => {
          if (error.status === 404) {
            // Todo: redirect to 404 page
          }
        }
      )
    ));
  }

}

回答1:


It should be,

<app-list [user]="username"></app-list>



回答2:


Alternatively you can use @ViewChild() decorator to achieve the below

export class UserComponent implements OnInit {
 @ViewChild(AppListCopmonent) appList: AppListComponent;

  ngOnInit() {   
      this.appList.user = this.username
 }  
}

Update based on chat : Before assigning the value check if the data is there as

this.apiService.getUser(params['username']).subscribe((response: Response) => {      
  if(response){
      console.log(response.json());
      this.username = response.json().username;
      this.reputation = response.json().reputation;
    });


来源:https://stackoverflow.com/questions/44869853/passing-data-from-parent-to-child-via-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!