【问题标题】:Passing data from Parent to Child via template通过模板将数据从父级传递给子级
【发布时间】:2017-07-02 10:34:14
【问题描述】:

我有一个模板用户,如下所示:

<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>

我的 app-list 组件如下所示:

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

  constructor() { }

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

}

用户名和信誉正确显示在页面上。但是用户名值没有正确传递给子组件应用列表,因为它只打印出一个空字符串。

如何将用户名传递给应用列表组件?

编辑

用户组件如下所示:

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
          }
        }
      )
    ));
  }

}

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    应该是,

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

    【讨论】:

    • 我也试过了。控制台只打印“未定义”
    • 它应该按照代码工作,你看到用户名打印在用户组件中
    • 是的。用户名和信誉显示在用户 component.html 上。我只是更改了用户 component.ts 中的代码,因此它不会从 api 加载数据,而只是直接分配 this.username = 'test' 并且该值被正确传递给列表组件。所以问题出在订阅电话上?
    • 是的!就是这样,你的 apiService 是什么样子的?
    • 组件为@Injectable(),方法为return this.http.get(host + username);
    【解决方案2】:

    或者你可以使用@ViewChild()装饰器来实现以下

    export class UserComponent implements OnInit {
     @ViewChild(AppListCopmonent) appList: AppListComponent;
    
      ngOnInit() {   
          this.appList.user = this.username
     }  
    }
    

    基于聊天更新:在分配值之前检查数据是否存在

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

    【讨论】:

    • 我不确定这会有什么帮助。我正在尝试将值从父母发送给孩子。如何访问 ListComponent 中的值?
    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2020-09-22
    • 1970-01-01
    • 2011-09-07
    • 2021-06-29
    • 1970-01-01
    • 2018-03-09
    • 2016-11-14
    相关资源
    最近更新 更多