Angular 2 - Changing Component Variable by Service Variable

Asked

Viewed 963 times

1

I would like to change my Component variable through a method performed in the service. The variable appears from true to false as desired in the console.log, but is not changed in the fixed variable in the Component. Variable to be changed: step0: boolean = true;

//SERVICE
import {
    Injectable
} from '@angular/core';

@Injectable()
export class StepsService {

    teste: string = 'texto de exemplo';
    step0: boolean;
    step1: boolean = true;

    constructor() {}

    proxStep1(): any {
        this.step0 = false;
        console.log(this.step0);
        return this.step0;
    }

    msgAlerta(): void {
        alert('Livro Angular 2 - Google - ' + this.teste);
    }
}    

//COMPONENT
import {
    Component,
    OnInit
} from '@angular/core';

import {
    StepsService
} from '../steps.service';

@Component({
    selector: 'app-step-0',
    templateUrl: './step-0.component.html',
    styleUrls: ['./step-0.component.css']
})
export class Step0Component implements OnInit {

    step0: boolean = true;

    constructor(public service: StepsService) {}

    ngOnInit() {}

    avancarStep1(): void {
        this.service.proxStep1();
    }

    enviarMsg(): void {
        this.service.msgAlerta();
    }
}

//TEMPLATE
<section class="step step0" *ngIf="step0 == true">
   <h2>Step-0 {{step0}}</h2>

   <button (click)="avancarStep1()">Avançar</button>
   <button (click)="enviarMsg()">Enviar Alerta</button>
</section>

1 answer

1


Your component template uses the property step0, referencing the property of the same name of its component.

In avancarStep1() in its component, do step0 receive the return of the method proxStep1() of the service.

avancarStep1(): void {
    this.step0 = this.service.proxStep1();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.