angular - 从另一个组件Angular 7中获取价值
问题描述
我必须将组件导航栏和表单对话框分开。我想在导航栏中使用 form-diyalog 中的值。
这是我的 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() {}
}
这是我的表单-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>
我可以在 form-diyalog 组件中编写 name.value,但我不能在导航栏组件中编写它。我怎样才能做到这一点?我试过@output,@input,但我做不到。
解决方案
您可以使用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
});
}
推荐阅读
- c++ - Boost Asio SSL 第二次以后无法接收数据(第一次正常)
- html - 元素被迫向右浮动,但不应该
- wordpress - WordPress Jupiter 主题 GDPR 配置
- r - 将两列转换为r中的日期和时间
- c++ - 通过引用返回包含对象的向量
- javascript - 在ionic3和angular4中使用socket.io创建聊天室
- javascript - jQuery如何将哈希值放入GET请求参数中
- php - 具有共享会话的 Yii2 高级应用程序不会在会话超时时自动登录
- java - 我想使用递归检查一个整数在数组中是否唯一
- iphone - iOS 中的 AdMob 原生高级广告收到无效响应