繁体   English   中英

Angular如何将ngModel数据从一个组件传递到另一个组件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM