I am learning Angular. I have a project that I use for learning purposes. I am on the section where I would like to add endless item types as it does in this example.
;(function () {
'use strict';
var DemoController = function($scope){
$scope.selectData = [
{
'name':'Rasmus Lerdorf',
'lang':'PHP'
},
{
'name':'James Gosling & Patrick Naughton',
'lang':'Java'
}
];
$scope.informations = [
{
'inputName' : '',
'inputSelect' : '',
'inputCheckbox' :'',
'optionsRadios' : ''
}
];
$scope.cloneItem = function () {
var itemToClone = {
'inputName': '',
'inputSelect': '',
'inputCheckbox':'',
'optionsRadios': ''
};
$scope.informations.push(itemToClone);
}
$scope.removeItem = function (itemIndex) {
$scope.informations.splice(itemIndex, 1);
}
$scope.submitForm = function() {
}
}
angular
.module('app', [])
.controller('DemoController' , DemoController);
DemoController.$inject = ['$scope'];
})();
I know that this example is old. Possibly from Angular 1. I couldn't find aywhere an example for element cloning.
I would appreciate if you can help me to understand how cloning elements works in Angular7.
You code is AngularJS, not Angular.
You have a data structure for your model.
export interface Developer {
name: string;
language: string;
selected: boolean;
}
Then you make a component with an array of them
developers: Developer[] = [{ name:'', language: '', selected: false }];
add() {
this.developers.push({ name:'', language: '', selected: false });
}
And in the view you ngFor over the array.
<ng-container *ngFor="let developer of developers;let i = index">
<input [name]="'name_' + i" [(ngModel)]="developer.name" type="text">
<select [name]="'language_' + i" [(ngModel)]="developer.language">
<option>PHP</option>
<option>Java</option>
<option>Angular</option>
<option>TypeScript</option>
</select>
<input [name]="'selected_' + i" [(ngModel)]="developer.selected" type="checkbox">
<br>
</ng-container>
<button (click)="add()">Add</button>
Best way to learn Angular is playing on StackBlitz https://stackblitz.com/edit/angular-ksgsnm?file=src/app/app.component.html