Brian
Brian

Reputation: 872

angular 6 + show hide element with ngIf doesn't work

I'm new to angular. I have the app.component.html like this:

<app-login *ngIf="!loggedIn"></app-login>
<section *ngIf="loggedIn" style="background:#EBF0F5;">
    <div class="container">       
        <div class="board">                    
            <msw-navbar ></msw-navbar>      
            <div class="tab-content">
                <!-- Nested view  -->
                <ui-view></ui-view>
            </div>
            <!-- End Content Area -->
        </div>
        <pre>{{ formData | json }}</pre>
    </div>
</section>

I want to show the login page and hide after login without any control or something. I have the login.ts

export class LoginComponent implements OnInit {
  logginIn: boolean = true;
}

in login click:

 login() {
    this.logginIn = true;
}

in app.component.ts

    export class AppComponent implements OnInit {      
    @Input() formData;
    loggedIn: boolean = false;
}

the login.html

  <div class="content">
  <form class="login-form">
      <h3 class="form-title">Login to your account</h3>
      <div class="alert alert-danger display-hide" style="display: none;">
        <button class="close" data-close="alert"></button>
        <span> Enter any username and password. </span>
      </div>
      <div class="form-group">
        <div class="input-icon">
          <i class="fa fa-user"></i>
          <input id="userName" name="userName" 
          class="form-control" required
          [(ngModel)]="user.userName"
          autofocus="autofocus" />
        </div>
      </div>
      <div class="form-group">
        <div class="input-icon">
          <i class="fa fa-lock"></i>
          <input id="password" name="password" 
          class="form-control" required 
          [(ngModel)]="user.password"
          type="password"/>
        </div>
      </div>

      <div class="row">
          <div class="col-xs-12">
            <div class="alert alert-danger" 
            *ngIf="securityObject &&
                   !securityObject.isAuthenticated">
              <p>Invalid User Name/Password.</p>
            </div>
          </div>
        </div>
      <br>
      <div class="text-right">
          <button class="btn-lg btn pull-right btnCol" (click)="login()">
              Login
            </button>  
      </div>
    </form>

What should I add in app.component to get the value from login component true or false? how the component communicate with each other? Thank you

Upvotes: 1

Views: 11407

Answers (1)

El Fadel Anas
El Fadel Anas

Reputation: 1721

In your app.component.html :

<app-login *ngIf="!loggedIn" (loggedIn)="isLogged($event)"></app-login>

in your login.component.ts :

@Output() loggedIn = new EventEmitter<boolean>();

login() {
 this.loggedIn.emit(true);
}

in your app.component.ts :

isLogged(logged:boolean) {
  this.loggedIn = logged;
}

I hope this will help

Upvotes: 2

Related Questions