实际上你不能这样做。在 Angular 中,我们将一切都视为组件。如果多个组件使用任何方法或属性,您可以遵循以下方法。因为您的组件不作为子父级相关。您可以按照方法 3 和 4 进行操作。
1. 父母对孩子和孩子对父母:通过@Input和@Output共享数据
这是在组件之间共享数据最常用的方式。它使用 @Input() 装饰器。您还可以使用 @Output() 装饰器将事件传递给父级。
父组件.ts:
@Component({
selector: 'app-parent',
template: `
<p>{{ message }}</p>
<app-child [input]="parentData" (output)="childMsg($event)"></app-child>`
})
export class ParentComponent{
message: string;
parentData = "message from parent"
childMsg(event) {
this.message = event;
}
}
子组件.ts:
@Component({
selector: 'app-child',
template: `
<p>{{ input }}</p>
<button (click)="submit()">Submit</button>
`
})
export class ChildComponent {
@Input() input: string;
@Output() output = new EventEmitter<string>();
message: string = "Hello World!"
submit() {
this.output.emit(this.message)
}
}
2. 孩子对家长:通过 ViewChild 共享数据
@ViewChild 装饰器允许将一个组件注入到另一个组件中,从而使父组件能够访问其属性和方法。
父组件.ts
@Component({
selector: 'app-parent',
template: `
Message: {{ childData }}
<app-child></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child;
childData: string;
ngAfterViewInit() {
this.childData = this.child.message
}
}
子组件.ts:
@Component({
selector: 'app-child',
})
export class ChildComponent {
childData = 'Hola Mundo!';
}
注意:我们使用 AfterViewInit lifeCycle 因为子视图在视图初始化之前不可用。
3.使用Service的不相关组件:在具有服务和行为主体的不相关组件之间共享数据
公共服务.ts:
@Injectable()
export class CommonService {
private data = new BehaviorSubject('default data');
data$ = this.data.asObservable();
changeData(data: string) {
this.data.next(data)
}
}
组件一.组件.ts:
@Component({
selector: 'app-component-one',
template: `<p>{{data}}</p>`
})
export class ComponentOneComponent implements OnInit {
data: string;
constructor(private service: CommonService) { }
ngOnInit() {
this.service.data$.subscribe(res => this.data = res)
}
}
组件-two.component.ts:
@Component({
selector: 'app-component-two',
template: `
<p>{{data}}</p>
<button (click)="newData()">Next Data</button>`
})
export class ComponentTwoComponent implements OnInit {
data: string;
constructor(private service: CommonService) { }
ngOnInit() {
this.service.data$.subscribe(res => this.data = res)
}
newData() {
this.service.data.next('Changed Data');
}
}
4、状态管理:使用 NgRx 在不相关的组件之间共享数据
您可以使用 NgRx 之类的存储来管理状态,您将在其中存储您的财产,然后在任何地方使用。我学习ngrx的时候就遵循了这个例子。