如何使输入表单数据显示在HTML中

问题描述 投票:0回答:1

此错误应该很简单,但是我是新来的有角度的人

我相信此代码应该进行一些更改

服务代码箱

import { Grade } from './../calculator/calculator.model';
import { Injectable } from '@angular/core';
import { Input } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class ResultService {
  @Input()
  grade: Grade = {
    name: '',
    grade1: null,
    grade2: null,
    grade3: null,
  };

  calcGrade(): void {
    let nota1 = this.grade.grade1 * 0.25;
    let nota2 = this.grade.grade2 * 0.25;
    let nota3 = this.grade.grade3 * 0.5;

    let conta = nota1 + nota2 + nota3;

    if (conta < 6.2) {
      console.log(
        `o aluno ${this.grade.name} foi reprovado com a nota ${conta}`
      );
    }
    if (conta >= 6.2) {
      console.log(
        `o aluno ${this.grade.name} foi aprovado com a nota ${conta}`
      );
    }
  }

  constructor() {}
}

当我单击按钮时,我想使用在另一个组件中输入的数据来调用该组件

HTML代码波纹管

或者我可以将代码服务添加到ts组件中

<div class="container">
  <div class="content">
    <h1>
      o aluno {{ grade.name }} tirou {{ grade.grade1 }} na primeira prova e
      {{ grade.grade2 }} na segunda prova
    </h1>
  </div>
</div>
angular service
1个回答
0
投票

您可以使用服务和行为主题在组件之间传输数据

让我们说,当您单击组件A中的某些按钮时,您需要将分数从组件A传递到组件B

  1. 我们可以在服务中定义该行为主题,
  2. 当您在组件A中单击该按钮时,只需发出或在旁边输入所输入的成绩信息,就可以>
  3. 在组件B的ngOnInit钩子中,我们可以订阅该行为主题,以获得该等级信息
  4. 服务中

gradeSubject = new BehaviorSubject<Grade>(null); // set the initial value of this behavior subject to null, you can set it anything you need

-在组分A中

  constructor(private resultService: ResultService) {} // inject the service in component A

  onClick(gradeInput) {
    // gradeInput is an object contains all the properties of the grade
    // design it as you want, maybe you pass name, grade1, grade2, and grade3 manually
    // the most important thing, that we need to pass this object through the behavior subject

    this.resultService.gradeSubject.next(gradeInput);
  };

-和组件B

  grade: Grade; // this is the grade object you used in the html

  constructor(private resultService: ResultService) {}

  ngOnInit() {
    // subscribe the behavior subject from the service to get the grade object

    this.resultService.gradeSubject.subscribe((gradeResult: Grade) => {
      // set the grade property in this component to the gradeResult
      this.grade = gradeResult;
    });

  }

希望有帮助

© www.soinside.com 2019 - 2024. All rights reserved.