[英]Angular how to pass ngModel data from one component to another?
我正在嘗試將ngModel數據從一個組件傳遞到另一個組件,其中第二個組件可以使用該數據在其html中執行功能。
我正在使用@Input(),但是我不知道如何通過超鏈接發送該數據。
home.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { BasePageComponent } from 'src/app/partials/base-page/base-page.component';
import { ActivatedRoute } from '@angular/router';
import { SurveyService } from 'src/app/services/survey.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent extends BasePageComponent implements OnInit {
@Input() surveyName: string;
surveys: any[];
constructor(
route: ActivatedRoute,
private surveyService: SurveyService) {
super(route);
}
ngOnInit() {
this.surveys = this.surveyService.getAll();
}
}
home.component.html
<div
class="col-4 col-sm-4 col-md-4 col-lg-4"
*ngFor="let survey of surveys"
>
<a class="btn btn-outline-secondary" href="/about" role="button">Begin Survey</a>
</div>
about.component.html
<input type="text" [(ngModel)]="surveyName" oninput="loadSurvey(surveyName)">
目前,這沒有任何作用。 我的預期結果是,當我單擊Begin Survey時 , about.component.html
將加載我在中使用loadSurvey(surveyName)
方法單擊的調查。
您可以使用共享組件。
在一個組件中,您可以偵聽更改,在onChange中,可以將信息傳輸到另一組件。
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message);
}
}
共享組件看起來像這樣簡單。
當您要發送消息時,可以使用
this.data.changeMessage('your info');
並在第二部分中接收它。
this.data.currentMessage.subscribe(message => {
console.log(message); //or whatever you want
}});
在這兩個組件中,您都可以導入服務,例如:私有數據:構造函數中的DataService。
更多信息,你可以觀看和閱讀此 。
在您的服務檔案中
import { BehaviorSubject } from 'rxjs';
surveyName : any;
private pathSource = new BehaviorSubject(window.location.pathname);
currentPath = this.pathSource.asObservable();
changeValue(message: string) {
this.pathSource.next(message)
}
在您的關於組件文件中
loadSurvey(surveyName){
this.service.changeValue(surveyName);
}
在您的home.component.ts文件中
ngOnInit() {
this.service.changeValue.subscribe(message => {
console.log(message); // you will get your survey name sended from home component
})
}
希望這個能對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.