I got an Angular 16.1 application. This application has a parent component with two children components:
Parent component inbox.ts:
@Component({
selector: 'inbox',
templateUrl: './templates/inbox.html'
})
export class Inbox implements OnInit {
tableRowsQuantity : number;
UserName : string;
constructor(private router: Router, private http:HttpClient, private route: ActivatedRoute) {}
ngOnInit() {
this.loadUserName();
this.loadInboxRowsQuantity(); // It uses http request by jquery with async:false
}
}
inbox.html:
<div>
{{inboxRowsQuantity}} <--- It shows the quantity. For this example, the value is 5
<childUser
[UserName]="UserName">
</childUser>
<br><br>
<childInbox
[inboxRowsQuantity]="inboxRowsQuantity"> <--- this is the instruction that it's not working. It's not passing the value
</childInbox>
</div>
Child component 1:
@Component({
selector: 'childUser',
templateUrl: '../templates/childUser.html'
})
export class ChildUser implements OnInit {
@Input() UserName = '';
constructor(private router: Router, private http:HttpClient, private route: ActivatedRoute) {}
ngOnInit() {
....
}
}
childUser.html:
<div>
<table cellpadding="0" cellspacing="0" height="100%">
<tr>
<th>User name:</th>
<td> {{UserName|titlecase}}</td>
</tr>
</table>
</div>
Child component 2:
@Component({
selector: 'childInbox',
templateUrl: '../templates/childInbox.html'
})
export class ChildInbox implements OnInit {
@Input() inboxRowsQuantity :number = 0;
constructor(private router: Router, private http:HttpClient, private route: ActivatedRoute) {}
ngOnInit() {
console.log('inboxRowsQuantity is:',this.inboxRowsQuantity); // always gives zero
}
}
childInbox.html:
<ul style="padding: 0px;">
<li class="menu-item">
<span style="list-style-type:none;"><i class="fa fa-inbox"></i>Inbox</span>
<span class="badge">{{inboxRowsQuantity}}</span>
</li>
</ul>
I will mention the following steps of loading the page:
- inbox.ts is processed. In this file tableRowsQuantity and UserName are obtained.
- childUser.ts is processed and chilUser.html is shown with user name value.
- childInbox.ts is processed. but {{inboxRowsQuantity}} of childInbox.html was not updated.
- {{inboxRowsQuantity}} is just shown in inbox.html but childboxInbox.html keeps showing zero.
It seems templates are loaded asynchronously. Besides, childUser.html is showing the correct information but childInbox.html isn’t.
What is it missing for this case?
>Solution :
Your HTML template is incorrect. The attributes for your child components are not part of the tag.
Update your HTML to the following:
<div>
<childUser [UserName]="UserName">
</childUser>
<br><br>
<childInbox [inboxRowsQuantity]="inboxRowsQuantity">
</childInbox>
</div>
See how I moved the [UserName] and [inboxRowsQuantity] inside the brackets for the childUser and childInbox tags?