내 서비스에서 "choosenModels"변수가 있는데,이 구성 요소는 app.component와 그의 하위 구성 요소 인 gallery.component의 두 가지 구성 요소에 사용됩니다. 버튼을 클릭하면 "choosenModels"값이 변경되지만 변경 사항은 자체 구성 요소에서만 나타납니다. 다른 구성 요소에 표시하는 방법?Angular2, 여러 구성 요소의 변수 자동 업데이트
Models.service.ts :
@Injectable()
export class ModelsService {
private _choosenModels: string = 'female';
_choosenModelsUpdate = new EventEmitter<string>();
getChoosenModels() {
return this._choosenModels;
}
setChoosenModels(value: string) {
this._choosenModels = value;
this._choosenModelsUpdate.emit(this._choosenModels);
}
}
두 구성 요소, 관계 부모 - 자식에 여기에 코드입니다.
<nav class="footer__nav">
<button
class="button"
(click)="onChangeModelsTeamClick('female')"
>
<div class="button__description">Modelki</div>
<i class="button__sign button__sign--female"></i>
</button>
<button
class="button button--male"
(click)="onChangeModelsTeamClick('male')"
>
<i class="button__sign button__sign--male"></i>
<div class="button__description button__description--male">Modele</div>
</button>
</nav>
하위 구성 요소 : gallery.component.ts : 부모
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [ ModelsService ],
})
export class AppComponent {
choosenModels: string = 'test';
constructor(private _modelsService: ModelsService) {}
ngOnInit() {
this.choosenModels = this._modelsService.getChoosenModels();
this._modelsService._choosenModelsUpdate.subscribe(
(choosenModels) => {
this.choosenModels = this._modelsService.getChoosenModels();
}
);
}
onChangeModelsTeamClick(value: string) {
console.log(value);
this._modelsService.setChoosenModels(value);
}
}
App.component.html을 App.component.ts
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.scss'],
providers: [
ModelsService,
],
})
export class GalleryComponent implements OnInit {
choosenModels: string;
constructor(private _modelsService: ModelsService) {}
ngOnInit() {
this.choosenModels = this._modelsService.getChoosenModels();
this._modelsService._choosenModelsUpdate.subscribe(
(choosenModels) => {
this.choosenModels = this._modelsService.getChoosenModels();
}
);
}
onChangeModelsTeamClick(value: string) {
this._modelsService.setChoosenModels(value);
}
}
gallery.component.html :
<nav class="navigation">
<button
class="button"
(click)="onChangeModelsTeamClick('female')"
[ngClass]="{'active': choosenModels=='female'}"
>
MODELKI
</button><!--
--><button
class="button"
(click)="onChangeModelsTeamClick('male')"
[ngClass]="{'active': choosenModels=='male'}"
>
MODELE
</button><!--
--><button
class="button"
(click)="onChangeModelsTeamClick('premium')"
[ngClass]="{'active': choosenModels=='premium'}"
>
PREMIUM
</button>
</nav>
예 !!! 당신은 위대하다! –