将数据传递给子组件

时间:2020-08-01 12:43:24

标签: angular

我正在尝试使用github API创建一个github搜索应用程序,但是在将数据传递给子组件时遇到一些问题。当用户单击视图配置文件按钮时,URL将是用户/用户ID,并且仅在子组件中显示配置文件详细信息。我看了一些有关它的教程,但是当我应用这些教程中显示的内容时,配置文件详细信息会列在主页上,而不是在子组件中。 我只需要个人资料组件中的个人资料详细信息。

home.component.html:

<input type="text" [(ngModel)]="profile" (keyup)="findProfile()" class="input">
<div>
  <ng-template [ngIf]="profile !== '' && user" >
    <img [src]="user.avatar_url" alt="" class="userAvatar">
    <p>Username: {{user.login}}</p>
    <p>Location: {{user.location}}</p>
    <p>E-mail: {{user.email}}</p>
    <p>Blog Link: {{user.blog}}</p>
    <p>Member Since: {{user.created_at}}</p>
    <button [routerLink]="['', user.login.toLowerCase(), user.id ]" class="viewProfileButton">View Profile</button>
  </ng-template>
</div>

home.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { HttpService } from '../http.service';
import { ProfileComponent } from './profile/profile.component';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  user: any;
  profile: any;
  constructor(private userData: HttpService) {}

  ngOnInit() {
  }

  findProfile() {
    this.userData.updateProfile(this.profile);
    this.userData.getUser().subscribe((result) => {
      this.user = result;
      console.warn(this.user);
    });
  }
}

profile.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpService } from 'src/app/http.service';


@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss']
})
export class ProfileComponent implements OnInit {
  userID: any;
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe(
      params => this.userID = params['userID']
    );
  }
}

1 个答案:

答案 0 :(得分:1)

最推荐的将数据从父组件传递到子组件的方法是在成角度的情况下使用@Input()@Output()装饰器。

Please review the official docs to know more about @Input and @Output decorators.