简体   繁体   English

将数据传递给子组件

[英]Passing data to child component

I'm trying to make a github search app with the github api but I have some problems with passing data to child component.我正在尝试使用 github api 制作 github 搜索应用程序,但我在将数据传递给子组件时遇到了一些问题。 When the user clicked the view profile button, URL will be user/userID and it will show the profile details only in the child component.当用户单击查看配置文件按钮时,URL 将是用户/用户 ID,它将仅在子组件中显示配置文件详细信息。 I watch some tutorials about it, but when I apply the ones shown in the tutorials, the profile details are listed on the main page not in the child component.我观看了一些关于它的教程,但是当我应用教程中显示的教程时,配置文件详细信息列在主页上而不是子组件中。 I only need profile details in the profile component.我只需要配置文件组件中的配置文件详细信息。

home.component.html:主页.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: 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: 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']
    );
  }
}

The most recommended way to pass the data from parent to child component is the use of @Input() and @Output() decorators in angular.最推荐的将数据从父组件传递到子组件的方法是在 angular 中使用@Input()@Output()装饰器。

Please review the official docs to know more about @Input and @Output decorators.请查看官方文档以了解有关 @Input 和 @Output 装饰器的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM