#angular
#angular
Вопрос:
У меня есть массив объектов marrayval, из этого массива мне нужно взять значения ‘country’ и нужно вставлять один за другим вместо всех элементов в arrayval после каждого щелчка.Например, для первого щелчка нужно нажать C1, затем для следующего щелчка нужно нажать c1, C2, затем c1, c2, c3 .. и так до конца. Вот код ниже https://stackblitz.com/edit/angular-cjzdqc?file=src/app/app.component.ts
app.component.html
<div (click)="getArray()">Click</div>
app.component.ts
import { Component,OnInit} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'testapp';
arrayval = [];
userName:any;
constructor() { }
marrayval = [{"id":1,"country":"C1","count":2},{"id":2,"country":"C2","count":1},{"id":3,"country":"C3","count":1}];
ngOnInit() {
}
getArray(){
this.marrayval.forEach((element) => {
console.log(element);
this.arrayval.push(element.country);
});
console.log(this.arrayval);
}
}
Ответ №1:
Это должно сработать —
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "testapp";
arrayval = [];
userName: any;
constructor() {}
marrayval = [
{ id: 1, country: "C1", count: 2 },
{ id: 2, country: "C2", count: 1 },
{ id: 3, country: "C3", count: 1 }
];
stackArray = [];
ngOnInit() {
this.stackArray = this.marrayval.reverse();
}
getArray() {
if (this.stackArray.length === 0) {
return;
}
this.arrayval.push(this.stackArray.pop().country);
console.log(this.arrayval);
}
}
Я также обновил здесь — https://stackblitz.com/edit/angular-cjzdqc?file=src/app/app.component.ts
Ответ №2:
Я думаю, это то, что вы хотите. Попробуйте это
marrayval = [
{ id: 1, country: "C1", count: 2 },
{ id: 2, country: "C2", count: 1 },
{ id: 3, country: "C3", count: 1 }
];
arrayval = [];
this.marrayval.reverse();
function getArray() {
if (this.marrayval.length === 0) {
return;
}
this.arrayval.push(this.marrayval.pop().country);
console.log(this.arrayval);
}
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
<button onClick="getArray()">Click me</button>
Ответ №3:
// click 1: [c1]
// click 2: [c1, c2]
// click 3: [c1, c2, c3]
// click 4: [c1, c2, c3]
// click 5: [c1, c2, c3]
this.arrayval =
this.marrayval
.filter((_, index) => index <= this.arrayval.length)
.map(element => element.country);
Комментарии:
1. Спасибо за ответ, куда мне нужно это добавить, я получаю некоторую ошибку getArray(){ this.marrayval = [ …this.marrayval, …this.marrayval.map(элемент => элемент.country) ] console.log(this.arrayval); }
2. Я не знаю, хотите ли вы это сделать. но я никогда не делаю ничего подобного. Потому что после слияния в одном списке есть 2 типа. Возможно, это ошибка типа typescript.
3. Я создал демо, не могли бы вы обновить здесь stackblitz.com/edit /…
4. Я только что обновил его. stackblitz.com/edit /…
5. Вы нажимаете все элементы c1, c2, c3 одновременно. но в соответствии с требованием нам нужно сначала нажать c1 только один раз, когда мы нажмем, затем c1, c2 один раз, когда мы нажмем, затем c1, c2, c3 один раз, когда мы нажмем..