2016-03-21 4 views
0

Здесь идет еще один вопрос Angular2 (TS).Angular2 - Измените Variabel в родительском компоненте?

В моем приложении у меня есть родительский компонент с кнопкой. (class="btn btn-success") Когда эта кнопка i щелкнула, я вызываю функцию createUserBool, которая изменяет состояние o Boolean createUserBool. Этот Boolean используется с *ngIf на компоненте ребенка, чтобы показать этот компонент. (<createuser [createUser]="createUserBool" *ngIf="createUserBool"></createuser>)

Компонент ребенок является «модальный» и я хочу использовать кнопку в этом «модальный», чтобы вызвать логическое и закрыть «модальный».

Я пробовал пару вещей, но я, похоже, только могу изменить переменные Ребенок из родителя, а не наоборот.

Я надеюсь, что кто-то может мне помочь. Я все еще новичок в Angular. Если у вас лучший способ добиться подобного результата, пожалуйста, не стесняйтесь просвещать меня!

Родитель Компонент:

//Imports from Librays 
import {Component, View, Input} from "angular2/core"; 
import {JSONP_PROVIDERS, HTTP_PROVIDERS} from 'angular2/http'; 

import {Http, Jsonp} from 'angular2/http'; 

//Component imports 
import {FooterComponent} from '../footer/footer.component'; 
import {HeaderComponent} from '../header/header.component'; 
import {CreateUserComponent} from './createuser.component'; 

//Pipe imports 
import {userType} from '../../pipes/userType.pipe'; 

//Service imports 
import {ApiHelper} from '../../services/api.service'; 

@Component({ 
    selector: 'useradministration', 
    providers: [HTTP_PROVIDERS, ApiHelper], 
}) 

@View({ 
    templateUrl: '../../templates/useradmin/useradmin.html', 
    directives: [HeaderComponent, FooterComponent, CreateUserComponent], 
    pipes: [userType], 
}) 

export class UserAdministration { 

    private alluserdata; 

    constructor(private ApiService: ApiHelper) { 
     ApiService.getAllUsers().subscribe(
      users => this.allusers(users) 
     ); 
    } 

    allusers(users){ 
     this.alluserdata = users; 
    } 

    createUserBool: boolean; 
    public onCreateToggle() { this.createUserBool = !this.createUserBool; console.log(this.createUserBool)} 
} 

Родитель Шаблон: (Некоторые из них)

<div class="page-container-bg-solid page-boxed page-md"> 

    <adnexio-header protected></adnexio-header> 

    <div class="container"> 
     //Soem content here 
    </div> 

    <createuser [createUser]="createUserBool" *ngIf="createUserBool"></createuser> 

    <adnexio-footer></adnexio-footer> 

</div> 

Детский компонент:

//Imports from angular2 
import {Component, View, ChangeDetectionStrategy, NgZone, Input} from "angular2/core"; 
import {Http, Headers, RequestOptions, JSONP_PROVIDERS, HTTP_PROVIDERS, Response} from 'angular2/http'; 
import {FORM_PROVIDERS, FormBuilder, Validators, ControlGroup, Control} from 'angular2/common'; 

import {Observable}             from 'rxjs/Observable'; 

//Component imports 
import {FooterComponent} from '../footer/footer.component'; 
import {HeaderComponent} from '../header/header.component'; 
import {UserAdministration} from './useradmin.component'; 
//Pipe imports 
import {userType} from '../../pipes/userType.pipe'; 

//Service imports 
import {ApiHelper} from '../../services/api.service'; 

@Component({ 
    selector: 'createuser', 
    providers: [HTTP_PROVIDERS, ApiHelper] 
}) 

@View({ 
    templateUrl: '../../templates/useradmin/createuser.html', 
    directives: [HeaderComponent, FooterComponent /*, UserAdministration*/], 
    pipes: [userType] 
}) 

export class CreateUserComponent { 

    @Input() createUser: boolean; 

    superDupererrorMessage = "No error"; 
    public usertypes; 
    form: ControlGroup; 

    constructor(public theApiHelper: ApiHelper, fb: FormBuilder) { 

     theApiHelper.getUserTypes().subscribe(types => { 
      this.usertypes = types; 
     }); 

     this.form = fb.group({ 
      "firstName": ["", Validators.required], 
      "lastName": ["", Validators.required], 
      "email": ["", Validators.required], 
      "type": ["", Validators.required], 
      "password": ["", Validators.required], 
      "confirmPassword": ["", Validators.required], 
     });   
    } 


    //Submit function: 
    public onSubmit() { 
     console.log(this.form.value); 
     this.theApiHelper.createUser(this.form.value) 
      .subscribe((err) => { 
       this.superDupererrorMessage = err 
       console.log(this.superDupererrorMessage); 
       }); 
    } 

    public createUserToggle(){ 
     this.createUser = !this.createUser; 
     console.log(this.createUser) 
    } 
} 

Детский шаблон: (Некоторые из них)

<div class="overlay"> 
    <div class="overlayContainer"> 

     <div class="container"> 
      <div class="row"> 
       <div class="col-md-12"> 
        <div class="portlet light "> 

         <div class="errorMessage alert alert-danger" > 
          <strong>Error!</strong> {{superDupererrorMessage}} 
         </div> 

         <div class="portlet-title"> 
          <div class="caption caption-md"> 
           <i class="icon-user font-green"></i> 
           <span class="caption-subject font-green bold uppercase">User Creation</span> 
           <span class="caption-helper">Create them users!</span> 
          </div> 
          <div class="actions"> 
           <button type="button" class="btn btn-danger" (click)="createUserToggle()">Cancel creation</button> 
          </div> 
         </div> 

        </div> 
       </div> 
      </div> 
     </div> 

    </div> 
</div> 

ответ

1

Вам нужно создать @Ouput подобное в компоненте CreateUserComponent ребенка:

@Input() createUser: boolean; 
@Input() createUserChange: EventEmitter<boolean> = new EventEmitter(); 

(...) 

public createUserToggle(){ 
    this.createUser = !this.createUser; 
    console.log(this.createUser) 
    this.createUserChange.emit(this.createUser); 
} 

, а затем рычаги два связывания, как это при использовании суб компонента в родительском одном:

<createuser [(createUser)]="createUserBool" *ngIf="createUserBool"></createuser> 

Этот путь вы сможете уведомить родителя, инициировав собственное событие (createUserChange).

+0

Большое спасибо! Это сделал трюк! - Конечно, вы имели в виду вывод не вход 2. время :) – Habber

2

С @output() вы можете уведомить родителя об изменениях. Если имя выходного такое же, как на входе, но с Change суффикса, вы можете использовать короткий ХЕНД двухстороннюю синтаксиса связывания [(name)]="xxx"

export class CreateUserComponent { 

    @Input() createUser: boolean; 
    @Output() createUserChange:EventEmitter<boolean> = new EventEmitter<boolean>(); 

    public createUserToggle(){ 
     this.createUser = !this.createUser; 
     this.createUserChange.emit(this.createUser); 
     console.log(this.createUser); 
    } 
} 
<createuser [(createUser)]="createUserBool" *ngIf="createUserBool"></createuser> 
Смежные вопросы