I'm trying to make a github search app with the github api but I have some problems with passing data to child component. 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. 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:
<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']
);
}
}
The most recommended way to pass the data from parent to child component is the use of @Input()
and @Output()
decorators in angular.
Please review the official docs to know more about @Input and @Output decorators.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.