Получить значение из другого компонента Angular 7 - PullRequest
0 голосов
/ 10 мая 2019

У меня должен быть отдельный компонент navbar и форма-diyalog.Я хочу использовать значение из формы-diyalog в navbar.

Это мой navbar.ts

import { Component, OnInit } from "@angular/core";
import { MenuItemModels } from "./models/MenuItemModel";

@Component({
  selector: "app-navbar",
  templateUrl: "./navbar.component.html",
  styleUrls: ["./navbar.component.css"]
})
export class NavbarComponent implements OnInit {
  MenuItem: MenuItemModels[] = [
    { name: "Anasayfam", link: "#" },
    { name: "Hakkımızda", link: "#" },
    { name: "Üniversitemiz", link: "#" },
    { name: "Fakültelerimiz", link: "#" },
    { name: "Bize Ulaşın", link: "#" }
  ];
  addItem() {
    let customObj = new MenuItemModels();
    customObj.name = customObj.link = "#";
    this.MenuItem.push(customObj);
  }

  deleteItem(i) {
    this.MenuItem.splice(i, 1);
  }

  constructor() {}

  ngOnInit() {}
}

Это мой form-diyalog.ts

import { Component, OnInit, Input, Output } from "@angular/core";
import { FormControl } from "@angular/forms";

@Component({
  selector: "app-form-diyalog",
  templateUrl: "./form-diyalog.component.html",
  styleUrls: ["./form-diyalog.component.css"]
})
export class FormDiyalogComponent implements OnInit {
  name = new FormControl("");

  constructor() {}

  ngOnInit() {}
}

и это form-diyalog.html

    <label>
    Menu Name:
    <input type="text" [formControl]="name">
    </label>

    <p>
    Value: {{ name.value }}
    </p>

Я могу написать name.value в компоненте form-diyalog, но я не могу это сделать в компоненте navbar.Как я могу этого добиться?Я попробовал @output, @input, но не смог.

1 Ответ

1 голос
/ 10 мая 2019

Вы можете использовать Rxjs subject для того же, вот пример того, как вы можете создать динамический предмет.поэтому каждый раз, когда вам не нужно создавать новую тему для передачи данных из другого компонента

BrodcastService.ts

interface Event {
  key: string;
  value: any;
}


@Injectable({
  providedIn: 'root'
})

export class Broadcaster {

  // subject 
  protected _eventsSubject = new Subject<Event>();
  constructor() {
  }

   broadcast(key: any, value: any) {
    this._eventsSubject.next({ key, value }); // here we are setting the key and value of our subject
   }

  on<T>(key: any): Observable<T> {
    return this._eventsSubject.asObservable()
            .pipe(
                filter(e => e.key === key),
                map(e => e.value)
            );
  }
}

ComponentOne.ts компонент, который вы хотите отправить данные другому компоненту

import { Broadcaster } from '../BrodcastService.service';
export class ComponentOne implements OnInit {
constructor(private broadcaster: Broadcaster) { }

someFunction() {
         this.broadcaster.broadcast('errorMessage', 'some error');
//         this.broadcaster.broadcast('errorMessage', {err: 'some error'});
// you can also pass the object
}

componentTwo.ts // это компонент, который потребляет субъект

import { Broadcaster } from '../BrodcastService.service';
export class componentTwo implements OnInit {
constructor(private broadcaster: Broadcaster) { }

someFunction() {
this.broadcaster.on('errorMessage').subscribe(response => { 
 console.log(response); // here you are getting the data from the other component 
});
}
...