No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Cómo usar Angular

12/28
Recursos

Aportes 46

Preguntas 8

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Así quedaría el código con el reto

<h2>{{ title }}</h2>
<form *ngFor="let movie of movies">
  <h3>{{ movie.name }}</h3>
  <button
    type="button"
    [disabled]="movie.quantity <= 0"
    (click)="removeMovieQuantity(movie.name)"
  >
    -
  </button>
  {{ movie.quantity }}
  <button
    type="button"
    [disabled]="movie.quantity >= movie.available"
    (click)="addMovieQuantity(movie.name)"
  >
    +
  </button>
</form>

Array con la informacion de las peliculas

[
            {
              name: "Avengers",
              available: 3,
              quantity: 0,
            },
            {
              name: "Terminator",
              available: 5,
              quantity: 0,
            },
          ]

En el type Movie hay que cambiar el tipo de dato Number por number, ya que con el Number no se puede utilizar el operador += o -=.

Personalmente prefiero la sintaxis de angular, react es una pesadilla visual

Mi solución al reto

App.component.html

<h2>{{title}}</h2>

<form *ngFor="let movie of movies">
  <h3>{{movie.name}}</h3>
  <img src="{{movie.url}}" width="100px" alt="" />
  <br />
  <button
    type="button"
    (click)="removeMovieQuantity(movie.name)"
    [disabled]="movie.quantity <= 0"
  >
    -
  </button>
  {{movie.quantity}}
  <button
    type="button"
    (click)="addMovieQuantity(movie.name)"
    [disabled]="movie.quantity >= movie.available"
  >
    +
  </button>
</form>

App.component.ts

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

type Movie = {
  name: String;
  available: Number;
  quantity: any;
  url: String;
};

type Movies = Array<Movie>;

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title: String = "Peliculas";
  movies: Movies = [
    {
      name: "Avengers",
      available: 3,
      quantity: 0,
      url: "https://dam.smashmexico.com.mx/wp-content/uploads/2018/04/24160210/lo-que-debes-recordar-avengers-infinity-war.jpg"
    },
    {
      name: "Terminator",
      available: 5,
      quantity: 0,
      url: "https://es.web.img3.acsta.net/pictures/16/02/12/15/14/218373.jpg",
    }
  ];

  addMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );
    this.movies[movieIndex].quantity += 1);
  }

  removeMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );
    this.movies[movieIndex].quantity -= 1;
  }
}

para los que actualmente no les funciona el código, añadir :any

(movieName: any)

Porque TypeScript es un lenguaje tipado?

TypeScript es un lenguaje tipado, pero es opcional. La razón por la cual Microsoft decidió hacerlo de esta forma, fue para evitar ciertos errores que pasaban muy frecuentemente con JavaScript, como el

undefined is not a function

Entonces, cuando el programador declara de manera explicita el tipo de dato de un elemento, estos errores son mas fáciles de detectar incluso desde el IDE

Angular se ve bastante complejo pero en lo personal me gusto su sintaxis por cierto aca dejo como quedaria el reto de los botones

<button
    type="button"
    (click)="removeMovieQuantity(movie.name)"
    [disabled]="movie.quantity <= 0"
  >
    -
  </button>
  {{ movie.quantity }}
  <button
    type="button"
    (click)="addMovieQuantity(movie.name)"
    [disabled]="movie.quantity >= movie.available"
  >
    +
  </button>

Me gusta que Angular sea con typescript, but a la vez siento que se me complica más su sintaxis xD

Que pesadilla TypeScript, demasiada cosa. 😵‍💫

app.component.ts

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

type Movie = {
  name: string, 
  available: number,
  quantity: number, 
};
type Movies = Array<Movie>;
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title: String = "Películas";
  movies: Movies  = [
    {
      name: 'Avengers',
      available: 3,
      quantity: 0,
    },
    {
      name: 'Terminator',
      available: 5,
      quantity: 0,
      }
  ];

  addMovieQuantity(movieName){
    const movieIndex = this.movies.findIndex(
      movie => movie.name === movieName
    );
    this.movies[movieIndex].quantity += 1;
  }

  removeMovieQuantity(movieName){
    const movieIndex = this.movies.findIndex(
      movie => movie.name === movieName
    );
    this.movies[movieIndex].quantity -= 1;
  }


}

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div>
  <h2>{{title}}</h2>

  <form *ngFor="let movie of movies">
    <h3>{{movie.name}}</h3>
    <button type="button" 
      (click)="removeMovieQuantity(movie.name)"
      [disabled]="movie.quantity <= 0"
      >-</button>
    {{ movie.quantity }}
    <button type="button" 
      (click)="addMovieQuantity(movie.name)"
      [disabled]="movie.quantity >= movie.available"
      >+</button>
  </form>
  
</div>

Me pareció mucho más complejo Angular ya veo porque su popularidad baja más y más cada vez…

Por otro lado aquí está el reto solucionado:

<h2>{{title}}</h2>

<form *ngFor="let movie of movies">
  <h3>{{movie.name}}</h3>
  <p>Available:</p>
  <button
    type="button"
    (click)="removeMovieQuantity(movie.name)"
    [disabled]="movie.quantity <= 0"
  >
    -
  </button>
  {{movie.quantity}}
  <button
    type="button"
    (click)="addMovieQuantity(movie.name)"
    [disabled]="movie.quantity >= movie.available"
  >
    +
  </button>
</form>

Codigo final de la clase:

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

type Movie = {
  name: String;
  available: Number;
  quantity: Number;
};

type Movies = Array<Movie>;

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "Películas";
  movies: Movies = [
    {
      name: "Avenger",
      available: 5,
      quantity: 0
    },
    {
      name: "Terminator",
      available: 3,
      quantity: 0
    }
  ];
  addMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );
    this.movies[movieIndex].quantity += 1;
  }
  removeMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );
    this.movies[movieIndex].quantity -= 1;
  }
}

<!--The content below is only a placeholder and can be replaced.-->
<div>
  <h1>
    {{ title }}
  </h1>
  <form *ngFor="let movie of movies">
    <h3>{{movie.name}}</h3>
    <button
      type="button"
      (click)="removeMovieQuantity(movie.name)"
      [disabled]="movie.quantity===0"
    >
      -
    </button>
    {{movie.quantity}}
    <button
      type="button"
      (click)="addMovieQuantity(movie.name)"
      [disabled]="movie.quantity===movie.available"
    >
      +
    </button>
  </form>
</div>

Reto:

  <button
    type="button"
    (click)="removeMovieQuantity(movie.name)"
    [disabled]="movie.quantity === 0" >
    -
  </button>

  {{ movie.quantity}}

  <button
    type="button"
    (click)="addMovieQuantity(movie.name)"
    [disabled]="movie.quantity === movie.available">
    +
  </button>

my code

Use lo que corresponde al [disabled]

<h2>{{ title }}</h2>

<form *ngFor="let movie of movies">
  <h3>{{ movie.name }}</h3>
  <button type="button" (click)="addMovieQuantity(movie.name)" [disabled]="movie.available <= movie.quantity">+</button>
  {{ movie.quantity }}
  <button type="button" (click)="removeMovieQuantity(movie.name)" [disabled]="0 >= movie.quantity">-</button>
</form>

Si les llega en estos tiempos a salir el error:

src/app/app.component.ts:30:20 - error TS7006: Parameter 'movieName' implicitly has an 'any' type.

Este error se debe a que TypeScript, el lenguaje de programación utilizado en Angular, está aplicando comprobaciones de tipo y requiere que se especifiquen los tipos de los parámetros de las funciones.

Para solucionar este error, puedes especificar explícitamente el tipo de ‘movieName’ como ‘string’ en la firma del método ‘addMovieQuantity’.

addMovieQuantity(movieName: string) {
  const movieIndex = this.movies.findIndex(
    (movie) => movie.name === movieName
  );
  this.movies[movieIndex].quantity += 1;
}

I did the example. Angular is steady being the best option for me. Nevetherless I will say that I spend 40 minutes trying to make the button work, at the end I erase the buggy code, re write and then work.

Not only re think o re read your code. Be an active part of the develpment. Be greater

Love always community

🚀 Un pedacito de mis notas 💚
Todas en mi GitHub

Qué es Angular y cómo se construyó

Tiene un sistema para crea componentes llamado engine modules, agrupan componentes que acuden a un mismo fin. Angular es patrocinado por google pero no depende de él.

En algún momento se decidió que angular se escribiría desde ero para implementar componentes. Así nació la versión 4. Desde ese momento se publican nuevas versiones compatibles con las anteriores.

Componente: lógica e interfaz e usuario con el que la interacción es real.

Incemental DOM: cada componente se convierte en una instrucción por lo que no se crean copias del DOM, así se ahorra memoria.

Angular se programa en TypeScript, es un lenguaje tipado, orientado a objetos por lo que se recomienda especificar el tipo de las variables.

En el archivo index.html se compila la aplicación con la etiqueta <app-root></app-root>

No me parece difícil Angular, es muy parecido como en FastApi manejan en grandes app’s la division de archivos en routers.

En Node según veo, se tiende a respetar la lógica de JS visualmente

con todo respeto mucho codigo pa hacer lo mismo que con react. se que es pq angular es oop y ademas react con el hook useState nos ayuda mucho con manejo de variables

Tengo una duda, está bien si envío como parametro para incrementar o decrementar directamente movie en vez de movie. name?

(click)="removeMovieQuantity(movie)"
  addMovieQuantity(movie: Movie) {
    movie.quantity += 1;
  }

¡¡¡Hecho!!!

<h2>
  {{title}}
</h2>

<form *ngFor="let movie of movies">
  <h3>{{movie.name}}</h3>

  <button type="button" (click)="removeMovieCantidad(movie.name)" [disabled]="movie.cantidad <= 0">-</button>
  {{movie.cantidad}}
  <button type="button" (click)="addMovieCantidad(movie.name)" [disabled]="movie.cantidad >= movie.disponibles">+</button>
</form>

El reto lo hice de esta forma:

<button
      type="button"
      (click)="removeMovieQuantity(movie.name)"
      [disabled]="movie.quantity == 0"
    >
      -
    </button>
    {{ movie.quantity }}
    <button
      type="button"
      (click)="addMovieQuantity(movie.name)"
      [disabled]="movie.quantity >= movie.available"
    >
      +
    </button>

Reto cumplido! 😁😁😁

<h2>{{title}}</h2>
<form *ngFor="let movie of movies">
  <h3>{{movie.name}}</h3>
  <button
    type="button"
    (click)="removeMovieQuantity(movie.name)"
    [disabled]="movie.quantity <= 0"
  >
    -
  </button>
  {{movie.quantity}}
  <button
    type="button"
    (click)="addMovieQuantity(movie.name)"
    [disabled]="movie.quantity >= movie.available"
  >
    +
  </button>
</form>

El reto quedaría asi
TS

import { ThisReceiver } from "@angular/compiler";
import { Component } from "@angular/core";

type Movie = {
  name: string;
  available: number;
  quantity: number;
};

type Movies = Array<Movie>;

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title: string = "Peliculas";
  movies: Movies = [
    {
      name: "Avengers",
      available: 3,
      quantity: 0
    },
    {
      name: "Terminator",
      available: 5,
      quantity: 0
    }
  ];

  addMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );

    this.movies[movieIndex].quantity += 1;
  }

  removeMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );

    this.movies[movieIndex].quantity -= 1;
  }
}

html

<h2>{{ title }}</h2>

<form *ngFor="let movie of movies">
  <h3>{{movie.name}}</h3>
  <button
    type="button"
    (click)="removeMovieQuantity(movie.name)"
    [disabled]="movie.quantity <= 0"
  >
    -
  </button>
  {{movie.quantity}}
  <button
    type="button"
    (click)="addMovieQuantity(movie.name)"
    [disabled]="movie.quantity >= movie.available"
  >
    +
  </button>
</form>

Para hacer una doble autenticación agregue este codigo para validar que los tickets no sean negativos ni que pasen el numero de tickets disponibles

addMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );
    if(this.movies[movieIndex].quantity === this.movies[movieIndex].available)
    {
      this.movies[movieIndex].available;
    } else {
      this.movies[movieIndex].quantity += 1;
    }
  }
  removeMovieQuantity(movieName) {
    const movieIndex = this.movies.findIndex(
      (movie) => movie.name === movieName
    );
    if(this.movies[movieIndex].quantity  > 0){
      this.movies[movieIndex].quantity -= 1;
    } else {

      this.movies[movieIndex].quantity = 0
    }
<h2>{{ title }}</h2>

<form *ngFor="let movie of movies">
  <h3>{{ movie.name }}</h3>
  <button type="button" (click)="removeMovieQuantity(movie.name)"
  [disabled] = "movie.quantity <= 0"
  >-</button>
  <label>{{ movie.quantity }}</label>
  <button type="button" (click)="addMovieQuantity(movie.name)"
  [disabled] = "movie.quantity >= movie.available"
  >+</button>
</form>
<h2>{{ title }}</h2>

<form *ngFor="let movie of movies">
  <h3>{{movie.name}}</h3>

  <button
    type="button"
    (click)="RemoveMovieQuantity(movie.name)"
    [disabled]="movie.quantity === 0"
  >
    -
  </button>
  {{movie.quantity}}
  <button
    type="button"
    (click)="addMovieQuantity(movie.name)"
    [disabled]="movie.quantity >= movie.available"
  >
    +
  </button>
</form>

Reto!!!

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div>
  <h1>{{ category }}</h1>
  <div *ngFor="let serie of series">
    <h3>{{ serie.name }}</h3>
    <h5>{{ serie.available }} Available</h5>
    <button
      type="button"
      (click)="removeAvailable(serie.name)"
      [disabled]="0 === serie.quantity"
    >
      -
    </button>
    {{ serie.quantity }}
    <button
      type="button"
      (click)="addAvailable(serie.name)"
      [disabled]="serie.quantity === serie.available"
    >
      +
    </button>
  </div>
</div>

app.component.ts

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

type Serie = {
  id: Number;
  name: String;
  available: Number;
  quantity: Number;
};
type Series = Array<Serie>;

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  category: String = "Series";
  series: Series = [
    {
      id: 1,
      name: "Game of Thrones",
      available: 10,
      quantity: 0
    },
    {
      id: 2,
      name: "Breaking Bad",
      available: 8,
      quantity: 0
    },
    {
      id: 3,
      name: "Mr. Robot",
      available: 8,
      quantity: 0
    },
    {
      id: 4,
      name: "Suits",
      available: 6,
      quantity: 0
    }
  ];
  addAvailable(name) {
    const index = this.series.findIndex((serie) => serie.name === name);
    this.series[index].quantity++;
  }
  removeAvailable(name) {
    const index = this.series.findIndex((serie) => serie.name === name);
    this.series[index].quantity--;
  }
}

Mejore mi código en una sola función

changeAvailable(name, e) {
    const index = this.series.findIndex((serie) => serie.name === name);
    e ? this.series[index].quantity++ : this.series[index].quantity--;
  }
<button
      type="button"
      (click)="changeAvailable(serie.name, false)"
      [disabled]="0 === serie.quantity"
    >
      -
    </button>
    {{ serie.quantity }}
    <button
      type="button"
      (click)="changeAvailable(serie.name, true)"
      [disabled]="serie.quantity === serie.available"
    >
      +
    </button>

Agreguen esta pequeña linea debajo del <h3> del .html y usen los botones 😄

<h5>Available:{{movie.available - movie.quantity}}</h5>

Siempre he trabajado con React Js y me pareció muy tedioso Angular

Listo

 <button type="button" (click)="removeMovieQuantity(movie.name)" [disabled]="movie.quantity <= 0">-</button>
  {{movie.quantity}}
  <button type="button" (click)="addMovieQuantity(movie.name)" [disabled]="movie.quantity >= movie.available">+</button>

Mi solución al reto, muy parecida a la que enviaron muchos pero con la diferencia de poner ==0 en el disabled del -

<h2>{{ title }}</h2>
<form *ngFor="let movie of movies">
  <h3>{{ movie.name }}</h3>
  <button
    type="button"
    [disabled]="movie.quantity == 0"
    (click)="removeMovieQuantity(movie.name)"
  >
    -
  </button>
  {{ movie.quantity }}
  <button
    type="button"
    [disabled]="movie.quantity >= movie.available"
    (click)="addMovieQuantity(movie.name)"
  >
    +
  </button>
</form>
<h2>Peliculas</h2>
<form *ngFor="let movie of movies">
  <h3>{{ movie.name }}</h3>
  <button
    type="button"
    [disabled]="movie.quantity <= 0"
    (click)="removeMovieQuantity(movie)"
  >
    -
  </button>
  {{ movie.quantity }}
  <button
    type="button"
    [disabled]="movie.quantity >= movie.available"
    (click)="addMovieQuantity(movie)"
  >
    +
  </button>
</form>
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  movies = [
    { name: "Avengers", available: 5, quantity: 0 },
    { name: "Wonder Woman", available: 15, quantity: 0 }
  ];

  removeMovieQuantity(movie) {
    movie.quantity--;
  }

  addMovieQuantity(movie) {
    movie.quantity++;
  }
}
import { Component } from "@angular/core";

interface IMovie {
  name: String;
  available: Number;
  quantity: Number;
}

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  movies: IMovie[] = [
    { name: "Avengers", available: 5, quantity: 0 },
    { name: "Wonder Woman", available: 15, quantity: 0 }
  ];

  removeMovieQuantity(movie) {
    movie.quantity--;
  }

  addMovieQuantity(movie) {
    movie.quantity++;
  }
}
Yo lo hice algo así![](https://static.platzi.com/media/user_upload/image-3ddad7fd-3f99-4206-aa9a-f4bd1bc61646.jpg)![](https://static.platzi.com/media/user_upload/image-46055472-6bcd-44c9-a246-6a9ea0f21c2b.jpg)
Creo que lo resolví algo diferente: ```js app.component.ts import { Component } from '@angular/core'; type Movie = { name: string; maxTickets: number; quantity: number; noMoreAllowed: boolean; noLessAllowed: boolean; }; type Movies = Array<Movie>; @Component({ selector: 'app-root', // template: `

Peliculas

`, templateUrl: './app.component.html', }) export class AppComponent { title: String = 'Peliculas'; movies: Movies = [ { name: 'Revengers', maxTickets: 12, quantity: 0, noMoreAllowed: false, noLessAllowed: false, }, { name: 'Spuder Moon', maxTickets: 10, quantity: 0, noMoreAllowed: false, noLessAllowed: false, }, { name: 'Baturu Man', maxTickets: 8, quantity: 0, noMoreAllowed: false, noLessAllowed: false, }, { name: 'Journey Rabbit', maxTickets: 2, quantity: 0, noMoreAllowed: false, noLessAllowed: false, }, { name: 'Blue Penter', maxTickets: 3, quantity: 0, noMoreAllowed: false, noLessAllowed: false, }, { name: 'River Gens, Mid Game', maxTickets: 5, quantity: 0, noMoreAllowed: false, noLessAllowed: false, }, { name: 'Finally, The One Piece', maxTickets: 10, quantity: 0, noMoreAllowed: false, noLessAllowed: false, }, ]; addMovieQuantity(movieName: string) { const movieIndex = this.movies.findIndex( (movie) => movie.name === movieName, ); if ( this.movies[movieIndex].quantity <= this.movies[movieIndex].maxTickets ) { this.movies[movieIndex].quantity += 1; this.movies[movieIndex].noLessAllowed = false; } else { this.movies[movieIndex].noMoreAllowed = true; } } removeMovieQuantity(movieName: string) { const movieIndex = this.movies.findIndex( (movie) => movie.name === movieName, ); if (this.movies[movieIndex].quantity > 0) { this.movies[movieIndex].quantity -= 1; this.movies[movieIndex].noMoreAllowed = false; } else { this.movies[movieIndex].noLessAllowed = true; } } } app.component.html

{{ title }}

<form *ngFor="let movie of movies">

{{ movie.name }}

<button type='button' (click)="removeMovieQuantity(movie.name)" [disabled]="movie.noLessAllowed" > - </button> {{ movie.quantity }} <button type='button' (click)="addMovieQuantity(movie.name)" [disabled]="movie.noMoreAllowed" > + </button> </form> ```
Mi solución `

{{ title }}

<form *ngFor="let movie of movies; index as movieIndex"> <h5>{{ movie.name }}</h5> <button type="button" [disabled]="movie.quantity <= 0" (click)="removeMovieQuantity(movieIndex)" > - </button> {{ movie.quantity }} <button type="button" [disabled]="movie.quantity >= movie.available" (click)="addMovieQuantity(movieIndex)" > + </button></form>`

no me gusto typescript :v

En TypeScript el tipado de las variables NUNCA debería hacerse con la primera letra en mayúscula para los tipos number, string, boolean, symbol y object. Es una mala practica. Es decir las variables deberían tener el tipado de la siguiente manera:

type Movie = {
	name: string;
	available: number;
	quantity: number;
}

// y movies también se puede tipar de  la siguiente manera:

type Movies = Movie[]; 

title: string = 'Películas'

https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html

c viene una nueva actualizacion de angular

crear zambox? que software has instalado?