如何将 AngularJS 代码写入 Angular 9?



我正在努力将Angular JS代码转换为Angular 9。这段代码在 Angular JS 上运行得很好。特别是我正在努力在ngModel中传递数组。

编辑感谢您的所有回复。但是,当我运行控制器代码时,代码会给出错误。

AngularJS 代码

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
Vendor Name: <input type="text"> <br> <br> Vendor Details: <textarea> </textarea> <br> <br>
<button ng-click="myFunc()">Click to enter Observations</button>
</form>
<div ng-repeat="observation in observations track by $index">
<br> <br>
<form>
Detailed Observation <input type="text" ng-model="observations[$index]">
<button type="submit" ng-click="nextObservation($index)" ng-if="$last"> Next Observation </button>
<button type="submit" ng-click="finish()" ng-if="$last"> Finish </button>
</form>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.observations = [];
$scope.myFunc = function() {
$scope.observations.push('');
}
$scope.nextObservation = function($index) {
$scope.observations[$index]
if ($scope.observations[$index]) {
$scope.observations.push('');
}
}
$scope.finish = function() {
console.log($scope.observations);
}
});
</script>
</body>
</html>

我从几个人那里得到了一个解决方案。我在收到的所有回复的帮助下进行了编码。最终的代码是在没有反应式表单帮助的情况下制作的。

app.component.html

<div>
Vendor Name: <input type="text" placeholder="Vendor Name" />
<br> <br>
Vendor Details: <textarea> </textarea> <br> <br>
<button (click)="addItem()">Click to enter Observations</button>
<br><br>
</div>
<div *ngFor="let observation of observations; let i=index; last as isLast; trackBy:trackByFn">
<div>
Detailed Observation {{i+1}}: <input type= "text" placeholder="Observation name" [(ngModel)]= "observations[i]">
<button type="submit" (click)="nextObservation(i)" *ngIf="isLast"> Next Observation </button>
<br /><br />
</div>

app.component.ts

import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
name = 'Angular ' + VERSION.major;
observations=[];
addItem()
{
this.observations.push('');
}
nextObservation(i)
{
if (this.observations[i])
{
this.observations.push('');
}
}
trackByFn(index: any, item: any) {
return index;
}
}

感谢您的所有回复。

<div *ngFor="let observation of observations; index as i; last as isLast">
<br> <br>
<form>
Detailed Observation <input type="text" [(ngModel)]="observations[i]">
<button type="submit" (click)="nextObservation(i)" *ngIf="isLast"> Next Observation </button>
<button type="submit" (click)="finish()" *ngIf="isLast"> Finish </button>
</form>
</div>

in component.ts file in class

observations: string[] = [];
ngOninit() {
this.observations.push('');
}
nextObservation($index) {
this.observations[$index]
if (this.observations[$index]) {
this.observations.push('');
}
}
finish() {
console.log(this.observations);
}

最新更新