برای انتقال اطلاعات بین فایل تایپاسکریپت و HTML روشهایی زیر قابل استفاده هستند:
1- انتقال اطلاعات از TS به HTML:
• استفاده از String Interpolation:
{{Var}}
export class AppComponent {
name: string = "shadman";
}
<p>Welcome {{name}}</p>
• استفاده از Property Binding:
[property]=”Var”
export class AppComponent {
name: string = "shadman";
isEnabled: boolean = true;
}
<button [disabled]="isEnabled">Click me</button>
2- انتقال اطلاعات از HTML به TS:
• استفاده از EventBinding:
(event)=”function”
export class AppComponent {
title = 'Test1 app';
name: string = "shadman";
isEnabled: boolean = true;
public onInputChanged(e: Event) {
console.log(e);
this.name = (<HTMLInputElement>e.target).value;
}
}
<input type="text" (input)="onInputChanged($event)" >
3- انتقال دوطرفه اطلاعات:
• استفاده از Two-way Binding:
[(ngModel)]=”Var”
<input type="text" [(ngModel)]="name">
برای استفاده از ngModel باید ماژول FormsModule را در بخش imports:[] وارد کرده و فایل مربوط به آن را نیز import کنید:
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
TestUserComponent,
UsersComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }