Building Reusable Components in different parts of an application or in a different application
Component API
Earlier, build a reusable favroite component.
But what if previously marked icon as favourite?
<favorite [isFavorite]=“…” </favorite>
Want to bind isFavroite property to some data
also, want to use event binding to subscribe event
need to define public API
mark properties as input or output
For e.g. Button’s API
<button [value]=“…” (click)=“…”> // button here is an input property
// click is an output property
We will now define API for a custom component
Input Properties
favorite.component.ts
import { Component,Input } from '@angular/core';
@Component({
selector: 'favorite',
template: // demonstrate class bindings below
`
<i
class="glyphicon"
[class.glyphicon-star-empty]="!isFavorite"
[class.glyphicon-star]="isFavorite"
(click)="onClick()">
</i>
`
})
export class FavoriteComponent {
//isFavorite = false; // currently private, not exposed to outside
@Input() isFavorite = false;
onClick(){
this.isFavorite = !this.isFavorite;
}
}
app.component.html
<h1>
{{title}}
</h1>
<favorite [isFavorite]="post.isFavorite">
</favorite>
app.component.ts
import { Component } from '@angular/core';
import {CoursesComponent} from './courses.component'
import {AuthorsComponent} from './authors.component'
import {FavoriteComponent} from './favorite.component'
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
directives: [CoursesComponent,AuthorsComponent,FavoriteComponent],
styleUrls: ['app.component.css']
})
export class AppComponent {
post = {
title:"Title",
isFavorite: true
}
}
If want to rename property, use aliasing, in favorite.component.ts
@Input('is-favorite') isFavorite = false;
In app.component.html
<favorite [is-favorite]="post.isFavorite">
No comments:
Post a Comment