javascript 儿童间的角化交流

eiee3dmh  于 2023-02-07  发布在  Java
关注(0)|答案(3)|浏览(167)

我正在做一个学生列表。输入字段、添加按钮和更新按钮在一个子组件中,而在另一个子组件中有一个带有删除和编辑按钮的列表。这两个都在父组件中处理。
当我点击编辑按钮,我希望输入字段有一个值,从该列表,并能够更新该列表。

父html

<ul>
    <app-list-item
      *ngFor="let studentName of students; let i = index"
      [name]="studentName"
      [index]="i"
      (deleteNameByIndex)="onemitDeleteNameByIndex($event)"
      (editNameById)="onemitEditNameById($event)"
    >
  </ul>

父.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  students = ['huzaifa', 'hunzila', 'waqar', 'sibte', 'shahzeen'];
  student = '';

  onemitAddNewName(newName: string) {
    this.students.push(newName);
  }
  onemitDeleteNameByIndex(index: number) {
    this.students.splice(index, 1);
  }
  onemitEditNameById(student: any) {
    this.student = student;
    console.log('app student :>> ', this.student);
  }
}

子项1 html

<input
  type="text"
  placeholder="enter name"
  [value]="name"
  (input)="oninputSetName($event)"
/>
{{ student }}
{{ name }}

<button (click)="onclickEmitNewName()">Add</button>
<button>Update</button>

子项1 .ts

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-list-form',
  templateUrl: './list-form.component.html',
  styleUrls: ['./list-form.component.css'],
})
export class ListFormComponent {
  name = '';
  @Output() newName = new EventEmitter<string>();
  @Input() student = '';

  oninputSetName(event: any) {
    this.name = event.target.value;
  }

  onclickEmitNewName() {
    this.newName.emit(this.name);
  }
  updateInput() {
    let obj = { name: this.student };
    console.log('list-form student :>> ', this.student);
  }
}

儿童2 html

{{ name }} -- {{ index }}
<button (click)="onclickDeleteName()">delete</button>
<button (click)="onclickEditName()">edit</button>

儿童2 .ts

@Component({
  selector: 'app-list-item',
  templateUrl: './list-item.component.html',
  styleUrls: ['./list-item.component.css'],
})
export class ListItemComponent {
  @Input() name = '';
  @Input() index = 0;

  @Output() deleteNameByIndex = new EventEmitter<number>();
  @Output() editNameById = new EventEmitter<any>();

  onclickDeleteName() {
    this.deleteNameByIndex.emit(this.index);
  }
  onclickEditName() {
    let obj = { index: this.index, name: this.name };
    this.editNameById.emit(obj);
  }
}
pftdvrlh

pftdvrlh1#

因为Angular 是通过引用传递。你可以利用它。当你这样做的时候,你甚至不需要发出改变的值。
例如,在Child 1处的代码中:而不是发出一个局部变量,你所能做的就是给@Input赋值。
下面是一个例子:

@Input existingStudentName: string;
localName: string = existingStudentName;

onUserUpdate(){
   existingStudentName = localName;
   //No need to emmit since existingStudentName is updated here
   //It will update in parent or anyone who refer it
}
<input type="text" [(ng-Model)]="localName">
<input type="button" (click)="onUserUpdate()">
gdx19jrr

gdx19jrr2#

或者甚至以更优雅的方式,您可以使用帮助服务来解决您的通信问题。
您可以在下面找到一个示例服务:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MessageService {
  private messageSource = new Subject<string>();
  currentMessage = this.messageSource.asObservable();

  constructor() {}

  changeMessage(message: string) {
    this.messageSource.next(message);
  }
}
import { Component } from '@angular/core';
import { MessageService } from './message.service';

@Component({
  selector: 'app-sender',
  template: `
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class SenderComponent {
  constructor(private messageService: MessageService) {}

  sendMessage() {
    this.messageService.changeMessage('Hello from Sender Component');
  }
}
import { Component } from '@angular/core';
import { MessageService } from './message.service';

@Component({
  selector: 'app-receiver',
  template: `
    <p>{{ message }}</p>
  `
})
export class ReceiverComponent {
  message: string;

  constructor(private messageService: MessageService) {
    this.messageService.currentMessage.subscribe(message => {
      this.message = message;
    });
  }
}
jv4diomz

jv4diomz3#

父级HTML

<section>
  <!-- input field where i enter my data -->
  <app-list-form
    (newName)="onemitAddNewName($event)"
    [student]="student"
    (updatedName)="updateThisNameInList($event)"
  ></app-list-form>

  <!-- rendering my list -->
  <ul>
    <app-list-item
      *ngFor="let studentName of students; let i = index"
      [name]="studentName"
      [index]="i"
      (deleteNameByIndex)="onemitDeleteNameByIndex($event)"
      (editNameById)="onemitEditNameById($event)"
      [
    ></app-list-item>
  </ul>
</section>

家长ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  students = ['huzaifa', 'hunzila', 'waqar', 'sibte', 'shahzeen'];
  student = null;

  onemitAddNewName(newName: string) {
    this.students.push(newName);
  }

  onemitDeleteNameByIndex(index: number) {
    this.students.splice(index, 1);
  }
  onemitEditNameById(student: any) {
    this.student = student;
  }

  updateThisNameInList(student: any) {
    let newName = student.name;
    let index = student.index;

    this.students.splice(index, 1, newName);
  }
}

子项1 html

<input
  type="text"
  placeholder="enter name"
  [(ngModel)]="name"
  (input)="oninputSetName($event)"
/>
<!-- {{ student?.name ?? "" }}
{{ name }} -->

<button (click)="onclickEmitNewName()">Add</button>
<button (click)="onclickEmitUpdateName()">Update</button>

儿童1 ts

import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
} from '@angular/core';

@Component({
  selector: 'app-list-form',
  templateUrl: './list-form.component.html',
  styleUrls: ['./list-form.component.css'],
})
export class ListFormComponent implements OnChanges {
  name = '';
  @Output() newName = new EventEmitter<string>();
  @Input() student: any = null;
  @Output() updatedName = new EventEmitter<any>();
  oninputSetName(event: any) {
    this.name = event.target.value;
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('list-form: changes happen ', changes);
    this.name = changes['student']?.currentValue?.name ?? '';
  }

  change(event: any) {
    this.name = event.target.value;
  }

  onclickEmitNewName() {
    this.newName.emit(this.name);
    this.name = '';
  }
  onclickEmitUpdateName() {
    // if (this.name == '') return;
    if (!this.name) return;
    this.updatedName.emit({
      name: this.name,
      index: this.student.index,
    });
  }
}

儿童2 html

<li>
  {{ name }} -- {{ index }}
  <button (click)="onclickDeleteName()">delete</button>
  <button (click)="onclickEditName()">edit</button>
</li>

儿童2 ts

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-list-item',
  templateUrl: './list-item.component.html',
  styleUrls: ['./list-item.component.css'],
})
export class ListItemComponent {
  @Input() name = '';
  @Input() index = 0;

  @Output() deleteNameByIndex = new EventEmitter<number>();
  @Output() editNameById = new EventEmitter<any>();
  onclickDeleteName() {
    this.deleteNameByIndex.emit(this.index);
  }
  onclickEditName() {
    let obj = {
      index: this.index,
      name: this.name,
    };
    this.editNameById.emit(obj);
  }
}

相关问题