我正在尝试将我存储在其中一个组件中的值传递给另一个组件,以便我的新组件可以使用我原来的选定值。现在我有一个如下文件:
符号picker.component.ts
import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'app-symbol-picker',
templateUrl: './symbol-picker.component.html',
styleUrls: ['./symbol-picker.component.scss']
})
export class SymbolPickerComponent implements OnInit {
selectionChoice: string;
equalsTxt = '=';
impliesTxt = '=>';
constructor() { }
ngOnInit() {
}
}

我在哪里设置" selectionChoice'在我的HTML中如下:
符号picker.component.html
<button (click)="selectionChoice = 'equals'">{{equalsTxt}}</button>
<button (click)="selectionChoice = 'implies'">{{impliesTxt}}</button>
&#13;
我想传递&quot; selectionChoice&#39;中的值。到一个新文件来使用它。例如,我正试图在此文件中获取值:
symbolPicker.ts
import {SymbolPickerComponent} from '../symbol-picker/symbol-picker.component';
export interface Config {
container: string;
selector: 'equals'|'implies'|'followsFrom';
}
export interface QuillInstance {
on: Function;
getText: Function;
}
export default class SymbolPicker {
symbolSelected = SymbolPickerComponent.selectionChoice;
quill: QuillInstance;
options: Config;
constructor(quill, options) {
this.quill = quill;
this.options = options;
const container = document.querySelector(this.options.container);
switch (this.options.selector) {
case 'equals': {
container.addEventListener('click', function() {
console.log('FRANK: EQUALS PRESSED');
quill.insertText(quill.getSelection(), '\n= 〈 〉');
});
break;
}
case 'implies': {
container.addEventListener('click', function() {
console.log('FRANK: IMPLIES PRESSED');
quill.insertText(quill.getSelection(), '\n=> 〈 〉');
});
break;
}
default: {
console.log('FRANK: selectionChoice set to non-understood value');
break;
}
}
}
}
&#13;
如何设置我新申请的&#39; symbolSelected&#39; symbolPicker.ts中的变量是symbol-picker.component.ts中selectionChoice的值吗?我最终尝试这样做,所以在我的editor.components.ts文件中,我也可以为我的选择器&#39;引用这个值。 symbolPicker中的部分如下:
this.modules = {
formula: true,
toolbar: true,
counter: { container: '#counter', unit: 'word' },
symbolPicker: { container: '#symbolCounter', selector: this.symbolSelected }
};
&#13;
我的想法是,当按下按钮在“等于”之间切换时,此选择器值会动态变化。并且&#39;暗示&#39;。
答案 0 :(得分:1)
有许多方法可以在组件之间共享数据。对于您的特定情况,您最好的选择是服务。构建服务以保留您要共享的值。
然后将服务注入任何需要设置值或读取值的组件。
我在这里有一个例子:https://github.com/DeborahK/MovieHunter-communication/tree/master/MH-Take4
在我的情况下,我分享当前选择的电影。以下是我的代码的一些片段。 (有关完整的代码示例,请参阅上面的URL。)
电影服务:
@Injectable()
export class MovieService {
currentMovie: IMovie | null;
// Other code here.
}
电影列表组件
在此组件中,用户选择一部电影:
export class MovieListComponent {
constructor(private movieService: MovieService) { }
onSelected(movie: IMovie): void {
this.movieService.currentMovie = movie;
}
// Other code here
}
电影明细组件
在此组件中,当用户在“电影列表”组件中选择不同的电影时,绑定会自动更改。
UI绑定到下面组件中定义的movie
属性。
export class MovieDetailComponent {
get movie(): IMovie | null {
return this.movieService.currentMovie;
}
constructor(private movieService: MovieService) {}
}
Angular的更改检测跟踪服务中currentMovie
更改并重新绑定值,调用上面显示的getter以及获取currentMovie
的当前值。