Сбой связи компонентов в Angular от дочернего к родительскому компоненту

avatar
Shivam Singh
9 августа 2021 в 01:18
147
0
0

Я пытаюсь применить @Output в своем примере проекта, следуя этому руководству. Я не могу заставить его работать. В консоли нет ошибок компиляции или какой-либо конкретной ошибки для этого. Я не могу понять, как продолжить отладку @Output с помощью инструментов разработчика. Ниже мои файлы.

app-component.ts


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  serverElements = [{type: 'server', name: 'testServer', content: 'Just a Server'}];
  constructor(){
    console.log(this.serverElements);
  }
  
  onServerAdded(serverData: {serverName: string, serverContent: string}) {
    console.log("Server Added");
    this.serverElements.push({
      type: 'server',
      name: serverData.serverName,
      content: serverData.serverContent
    });
    console.log("Server Added");
  }

  onBlueprintAdded(blueprintData: {serverName: string, serverContent: string}) {
    this.serverElements.push({
      type: 'blueprint',
      name: blueprintData.serverName,
      content: blueprintData.serverContent
    });
  }



}

app-component.html

  <app-cockpit (serverAdded)="onServerAdded($event)"
  (blueprintAdded)="onBlueprintAdded($event)"></app-cockpit>
  <hr>
  <div class="row">
    <div class="col-xs-12">
      <app-server-element *ngFor="let serverElement of serverElements" [element] = "serverElement"></app-server-element>
    </div>
  </div>
</div>

cockpit-component.ts


@Component({
  selector: 'app-cockpit',
  templateUrl: './cockpit.component.html',
  styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
  @Output() serverAdded = new EventEmitter<{serverName: string, serverContent: string}>();
  @Output() blueprintAdded = new EventEmitter<{blueprintName: string, blueprintContent: string}>();
  newServerName = '';
  newServerContent = '';
  constructor() { }

  ngOnInit(): void {
  }
  onAddServer() {
    console.log(this.newServerContent);
    console.log(this.newServerName);
    this.serverAdded.emit({
      serverName:this.newServerName, 
      serverContent:this.newServerContent
    });
  }

  onAddBlueprint() {
    this.blueprintAdded.emit({
      blueprintName:this.newServerName, 
      blueprintContent:this.newServerContent
    });
  }
}

cockpit-component.html

    <div class="col-xs-12">
      <p>Add new Servers or blueprints!</p>
      <label>Server Name</label>
      <input type="text" class="form-control" [(ngModel)]="newServerName">
      <label>Server Content</label>
      <input type="text" class="form-control" [(ngModel)]="newServerContent">
      <br>
      <button
        class="btn btn-primary"
        (click)="onAddServer()">Add Server</button>
      <button
        class="btn btn-primary"
        (click)="onAddBlueprint()">Add Server Blueprint</button>
    </div>
  </div>

Я вижу, что консоль выводит в браузере файл cockpit-component.ts, но это не приводит к вызову метода onServerAdded() в компоненте приложения. enter image description here

Теперь все работает после повторного запуска angular и vscode enter image description here

Источник
CodeWarrior
9 августа 2021 в 04:34
0

Я не вижу причины, почему это не работает. Можете ли вы создать проект на StackBlitz?

Shivam Singh
9 августа 2021 в 23:13
0

stackblitz.com/edit/angular-yk7ssu?file=src/styles.css вот он. Я не знаю, почему это работает на stackblitz ... когда я снова запустил свой локальный код после перезапуска vscode, он тоже работает там.

Ответы (0)