Compare commits
106 Commits
traducir-b
...
master
Author | SHA1 | Date | |
---|---|---|---|
80073944a1 | |||
a2aa45d3c7 | |||
0731c7f634 | |||
cf2d40e359 | |||
0c47b7184c | |||
752100487b | |||
7a183c9920 | |||
eac35a64e1 | |||
0348f47f62 | |||
79da3e8cd2 | |||
67b431603a | |||
604bd6e1cb | |||
fdf572b3c5 | |||
f6936406ca | |||
a4909d6aa0 | |||
600af0a5f6 | |||
a0fcc0b839 | |||
cf6efd91ae | |||
ee02855bd5 | |||
53fd049d12 | |||
a025e98ede | |||
768f81627e | |||
c2924a10e7 | |||
5af3281103 | |||
0496e59a10 | |||
6f07ef5236 | |||
0f9ed1d7d6 | |||
3aa0ca984c | |||
77832458c9 | |||
e10a578603 | |||
b142d33bbe | |||
bcabf710d0 | |||
a725fe261a | |||
ebee38994f | |||
6ebb0246ab | |||
c7a054fa31 | |||
6ff6acbb21 | |||
8a09cb9794 | |||
eeb59b4f4d | |||
7afbc3a1c1 | |||
3da8ebf27e | |||
7e33d531ae | |||
32577820f4 | |||
3686c640d6 | |||
cbe53247fa | |||
bbbae1065a | |||
b5c3bb998d | |||
4ff7aeadbb | |||
86eaf57d53 | |||
ff7b7a9c2f | |||
dea267e5c8 | |||
07200be358 | |||
45e6bb4a74 | |||
b44f7b1a5c | |||
3c9c40c4b7 | |||
15bb08eea6 | |||
10953bddcb | |||
7b87a797ed | |||
4ea5a19a10 | |||
ee263f3b97 | |||
f73846cd6b | |||
b2fd28d2b0 | |||
05535d985b | |||
4dc8aa2a27 | |||
3d084ac910 | |||
f8678d7513 | |||
c50136e2cb | |||
c3b4e0f37e | |||
4d33c41e92 | |||
eff4e3e3c2 | |||
e6c7536d62 | |||
5f4a06039e | |||
05b9bb71b1 | |||
c7cae616e0 | |||
14daffecc5 | |||
f6ae7d4f49 | |||
316d9d5c34 | |||
ba99c7792a | |||
66a2af0c77 | |||
ab87527e1d | |||
a0486577a8 | |||
6f4c65c029 | |||
295f3796c6 | |||
6362ec46d5 | |||
de2b1c4bb4 | |||
6aad16e11f | |||
78b657e8f3 | |||
ee9e65ecb1 | |||
5341121fde | |||
265581e525 | |||
06da025393 | |||
317bbd8f46 | |||
9cb99bbaa8 | |||
8a70ac0950 | |||
9956446ad7 | |||
f0865de125 | |||
5cb6779305 | |||
1e2e9201b2 | |||
6062e658db | |||
eca92ea193 | |||
3177ce1f35 | |||
faa17f8959 | |||
d42a09e9b6 | |||
408d38b223 | |||
333a1266cc | |||
a4912ff297 |
@ -30,11 +30,6 @@ var_4: &cache_key_fallback v7-angular-node-12-{{ checksum ".bazelversion" }}
|
||||
var_3_win: &cache_key_win v7-angular-win-node-12-{{ checksum ".bazelversion" }}-{{ checksum "yarn.lock" }}-{{ checksum "WORKSPACE" }}-{{ checksum "packages/bazel/package.bzl" }}-{{ checksum "aio/yarn.lock" }}
|
||||
var_4_win: &cache_key_win_fallback v7-angular-win-node-12-{{ checksum ".bazelversion" }}
|
||||
|
||||
# Cache key for the `components-repo-unit-tests` job. **Note** when updating the SHA in the
|
||||
# cache keys also update the SHA for the "COMPONENTS_REPO_COMMIT" environment variable.
|
||||
var_5: &components_repo_unit_tests_cache_key v9-angular-components-09e68db8ed5b1253f2fe38ff954ef0df019fc25a
|
||||
var_6: &components_repo_unit_tests_cache_key_fallback v9-angular-components-
|
||||
|
||||
# Workspace initially persisted by the `setup` job, and then enhanced by `build-npm-packages` and
|
||||
# `build-ivy-npm-packages`.
|
||||
# https://circleci.com/docs/2.0/workflows/#using-workspaces-to-share-data-among-jobs
|
||||
@ -156,27 +151,6 @@ commands:
|
||||
git config --global url."ssh://git@github.com".insteadOf "https://github.com" || true
|
||||
git config --global gc.auto 0 || true
|
||||
|
||||
init_saucelabs_environment:
|
||||
description: Sets up a domain that resolves to the local host.
|
||||
steps:
|
||||
- run:
|
||||
name: Preparing environment for running tests on Sauce Labs.
|
||||
command: |
|
||||
# For SauceLabs jobs, we set up a domain which resolves to the machine which launched
|
||||
# the tunnel. We do this because devices are sometimes not able to properly resolve
|
||||
# `localhost` or `127.0.0.1` through the SauceLabs tunnel. Using a domain that does not
|
||||
# resolve to anything on SauceLabs VMs ensures that such requests are always resolved
|
||||
# through the tunnel, and resolve to the actual tunnel host machine (i.e. the CircleCI VM).
|
||||
# More context can be found in: https://github.com/angular/angular/pull/35171.
|
||||
setPublicVar SAUCE_LOCALHOST_ALIAS_DOMAIN "angular-ci.local"
|
||||
setSecretVar SAUCE_ACCESS_KEY $(echo $SAUCE_ACCESS_KEY | rev)
|
||||
- run:
|
||||
# Sets up a local domain in the machine's host file that resolves to the local
|
||||
# host. This domain is helpful in Sauce Labs tests where devices are not able to
|
||||
# properly resolve `localhost` or `127.0.0.1` through the sauce-connect tunnel.
|
||||
name: Setting up alias domain for local host.
|
||||
command: echo "127.0.0.1 $SAUCE_LOCALHOST_ALIAS_DOMAIN" | sudo tee -a /etc/hosts
|
||||
|
||||
# Normally this would be an individual job instead of a command.
|
||||
# But startup and setup time for each individual windows job are high enough to discourage
|
||||
# many small jobs, so instead we use a command for setup unless the gain becomes significant.
|
||||
@ -272,109 +246,8 @@ jobs:
|
||||
- run: yarn -s tslint
|
||||
- run: yarn -s ng-dev format changed $CI_GIT_BASE_REVISION --check
|
||||
- run: yarn -s ts-circular-deps:check
|
||||
- run: yarn -s ng-dev pullapprove verify
|
||||
- run: yarn -s ng-dev commit-message validate-range --range $CI_COMMIT_RANGE
|
||||
|
||||
test:
|
||||
executor:
|
||||
name: default-executor
|
||||
# Now that large integration tests are running locally in parallel (they can't run on RBE yet
|
||||
# as they require network access for yarn install), this test is running out of memory
|
||||
# consistently with the xlarge machine.
|
||||
# TODO: switch back to xlarge once integration tests are running on remote-exec
|
||||
resource_class: 2xlarge+
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- install_chrome_libs
|
||||
- install_java
|
||||
- run:
|
||||
command: yarn bazel test //... --build_tag_filters=-ivy-only --test_tag_filters=-ivy-only
|
||||
no_output_timeout: 20m
|
||||
|
||||
# Temporary job to test what will happen when we flip the Ivy flag to true
|
||||
test_ivy_aot:
|
||||
executor:
|
||||
name: default-executor
|
||||
resource_class: xlarge
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- install_chrome_libs
|
||||
# We need to explicitly specify the --symlink_prefix option because otherwise we would
|
||||
# not be able to easily find the output bin directory when uploading artifacts for size
|
||||
# measurements.
|
||||
- run:
|
||||
command: yarn test-ivy-aot //... --symlink_prefix=dist/
|
||||
no_output_timeout: 20m
|
||||
|
||||
# Publish bundle artifacts which will be used to calculate the size change. **Note**: Make
|
||||
# sure that the size plugin from the Angular robot fetches the artifacts from this CircleCI
|
||||
# job (see .github/angular-robot.yml). Additionally any artifacts need to be stored with the
|
||||
# following path format: "{projectName}/{context}/{fileName}". This format is necessary
|
||||
# because otherwise the bot is not able to pick up the artifacts from CircleCI. See:
|
||||
# https://github.com/angular/github-robot/blob/master/functions/src/plugins/size.ts#L392-L394
|
||||
- store_artifacts:
|
||||
path: dist/bin/packages/core/test/bundling/hello_world/bundle.min.js
|
||||
destination: core/hello_world/bundle
|
||||
- store_artifacts:
|
||||
path: dist/bin/packages/core/test/bundling/todo/bundle.min.js
|
||||
destination: core/todo/bundle
|
||||
- store_artifacts:
|
||||
path: dist/bin/packages/core/test/bundling/hello_world/bundle.min.js.br
|
||||
destination: core/hello_world/bundle.br
|
||||
- store_artifacts:
|
||||
path: dist/bin/packages/core/test/bundling/todo/bundle.min.js.br
|
||||
destination: core/todo/bundle.br
|
||||
|
||||
# NOTE: This is currently limited to master builds only. See the `monitoring` configuration.
|
||||
saucelabs_view_engine:
|
||||
executor:
|
||||
name: default-executor
|
||||
# In order to avoid the bottleneck of having a slow host machine, we acquire a better
|
||||
# container for this job. This is necessary because we launch a lot of browsers concurrently
|
||||
# and therefore the tunnel and Karma need to process a lot of file requests and tests.
|
||||
resource_class: xlarge
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- init_saucelabs_environment
|
||||
- run:
|
||||
name: Run Bazel tests on Saucelabs with ViewEngine
|
||||
# See /tools/saucelabs/README.md for more info
|
||||
command: |
|
||||
yarn bazel run //tools/saucelabs:sauce_service_setup
|
||||
TESTS=$(./node_modules/.bin/bazelisk query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "ivy-only", ...) except attr("tags", "fixme-saucelabs-ve", ...)')
|
||||
yarn bazel test --config=saucelabs ${TESTS}
|
||||
yarn bazel run //tools/saucelabs:sauce_service_stop
|
||||
no_output_timeout: 40m
|
||||
- notify_webhook_on_fail:
|
||||
webhook_url_env_var: SLACK_DEV_INFRA_CI_FAILURES_WEBHOOK_URL
|
||||
|
||||
# NOTE: This is currently limited to master builds only. See the `monitoring` configuration.
|
||||
saucelabs_ivy:
|
||||
executor:
|
||||
name: default-executor
|
||||
# In order to avoid the bottleneck of having a slow host machine, we acquire a better
|
||||
# container for this job. This is necessary because we launch a lot of browsers concurrently
|
||||
# and therefore the tunnel and Karma need to process a lot of file requests and tests.
|
||||
resource_class: xlarge
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- init_saucelabs_environment
|
||||
- run:
|
||||
name: Run Bazel tests on Saucelabs with Ivy
|
||||
# See /tools/saucelabs/README.md for more info
|
||||
command: |
|
||||
yarn bazel run //tools/saucelabs:sauce_service_setup
|
||||
TESTS=$(./node_modules/.bin/bazelisk query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "no-ivy-aot", ...) except attr("tags", "fixme-saucelabs-ivy", ...)')
|
||||
yarn bazel test --config=saucelabs --config=ivy ${TESTS}
|
||||
yarn bazel run //tools/saucelabs:sauce_service_stop
|
||||
no_output_timeout: 40m
|
||||
- notify_webhook_on_fail:
|
||||
webhook_url_env_var: SLACK_DEV_INFRA_CI_FAILURES_WEBHOOK_URL
|
||||
|
||||
test_aio:
|
||||
executor: default-executor
|
||||
steps:
|
||||
@ -393,10 +266,6 @@ jobs:
|
||||
- run: yarn --cwd aio test-pwa-score-localhost $CI_AIO_MIN_PWA_SCORE
|
||||
# Run accessibility tests
|
||||
- run: yarn --cwd aio test-a11y-score-localhost
|
||||
# Check the bundle sizes.
|
||||
- run: yarn --cwd aio payload-size
|
||||
# Run unit tests for Firebase redirects
|
||||
- run: yarn --cwd aio redirects-test
|
||||
|
||||
deploy_aio:
|
||||
executor: default-executor
|
||||
@ -426,8 +295,6 @@ jobs:
|
||||
- run: yarn --cwd aio e2e --configuration=ci
|
||||
# Run PWA-score tests
|
||||
- run: yarn --cwd aio test-pwa-score-localhost $CI_AIO_MIN_PWA_SCORE
|
||||
# Check the bundle sizes.
|
||||
- run: yarn --cwd aio payload-size aio-local<<# parameters.viewengine >>-viewengine<</ parameters.viewengine >>
|
||||
|
||||
test_aio_tools:
|
||||
executor: default-executor
|
||||
@ -441,26 +308,6 @@ jobs:
|
||||
- run: yarn --cwd aio tools-test
|
||||
- run: ./aio/aio-builds-setup/scripts/test.sh
|
||||
|
||||
test_docs_examples:
|
||||
parameters:
|
||||
viewengine:
|
||||
type: boolean
|
||||
default: false
|
||||
executor:
|
||||
name: default-executor
|
||||
resource_class: xlarge
|
||||
parallelism: 5
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- install_chrome_libs
|
||||
# Install aio
|
||||
- run: yarn --cwd aio install --frozen-lockfile --non-interactive
|
||||
# Run examples tests. The "CIRCLE_NODE_INDEX" will be set if "parallelism" is enabled.
|
||||
# Since the parallelism is set to "5", there will be five parallel CircleCI containers.
|
||||
# with either "0", "1", etc as node index. This can be passed to the "--shard" argument.
|
||||
- run: yarn --cwd aio example-e2e --setup --local <<# parameters.viewengine >>--viewengine<</ parameters.viewengine >> --cliSpecsConcurrency=5 --shard=${CIRCLE_NODE_INDEX}/${CIRCLE_NODE_TOTAL} --retry 2
|
||||
|
||||
# This job should only be run on PR builds, where `CI_PULL_REQUEST` is not `false`.
|
||||
aio_preview:
|
||||
executor: default-executor
|
||||
@ -489,7 +336,6 @@ jobs:
|
||||
name: Wait for preview and run tests
|
||||
command: node aio/scripts/test-preview.js $CI_PULL_REQUEST $CI_COMMIT $CI_AIO_MIN_PWA_SCORE
|
||||
|
||||
|
||||
# The `build-npm-packages` tasks exist for backwards-compatibility with old scripts and
|
||||
# tests that rely on the pre-Bazel `dist/packages-dist` output structure (build.sh).
|
||||
# Having multiple jobs that independently build in this manner duplicates some work; we build
|
||||
@ -501,7 +347,7 @@ jobs:
|
||||
build-npm-packages:
|
||||
executor:
|
||||
name: default-executor
|
||||
resource_class: xlarge
|
||||
resource_class: medium
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
@ -523,246 +369,6 @@ jobs:
|
||||
- "~/bazel_repository_cache"
|
||||
- "~/.cache/bazelisk"
|
||||
|
||||
# Build the ivy npm packages.
|
||||
build-ivy-npm-packages:
|
||||
executor:
|
||||
name: default-executor
|
||||
resource_class: xlarge
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- run: node scripts/build/build-ivy-npm-packages.js
|
||||
|
||||
# Save the npm packages from //packages/... for other workflow jobs to read
|
||||
- persist_to_workspace:
|
||||
root: *workspace_location
|
||||
paths:
|
||||
- ng/dist/packages-dist-ivy-aot
|
||||
- ng/dist/zone.js-dist-ivy-aot
|
||||
|
||||
# This job creates compressed tarballs (`.tgz` files) for all Angular packages and stores them as
|
||||
# build artifacts. This makes it easy to try out changes from a PR build for testing purposes.
|
||||
# More info CircleCI build artifacts: https://circleci.com/docs/2.0/artifacts
|
||||
#
|
||||
# NOTE: Currently, this job only runs for PR builds. See `publish_snapshot` for non-PR builds.
|
||||
publish_packages_as_artifacts:
|
||||
executor: default-executor
|
||||
environment:
|
||||
NG_PACKAGES_DIR: &ng_packages_dir 'dist/packages-dist'
|
||||
NG_PACKAGES_ARCHIVES_DIR: &ng_packages_archives_dir 'dist/packages-dist-archives'
|
||||
ZONEJS_PACKAGES_DIR: &zonejs_packages_dir 'dist/zone.js-dist'
|
||||
ZONEJS_PACKAGES_ARCHIVES_DIR: &zonejs_packages_archives_dir 'dist/zone.js-dist-archives'
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
# Publish `@angular/*` packages.
|
||||
- run:
|
||||
name: Create artifacts for @angular/* packages
|
||||
command: ./scripts/ci/create-package-archives.sh $CI_BRANCH $CI_COMMIT $NG_PACKAGES_DIR $NG_PACKAGES_ARCHIVES_DIR
|
||||
- store_artifacts:
|
||||
path: *ng_packages_archives_dir
|
||||
destination: angular
|
||||
# Publish `zone.js` package.
|
||||
- run:
|
||||
name: Create artifacts for zone.js package
|
||||
command: ./scripts/ci/create-package-archives.sh $CI_BRANCH $CI_COMMIT $ZONEJS_PACKAGES_DIR $ZONEJS_PACKAGES_ARCHIVES_DIR
|
||||
- store_artifacts:
|
||||
path: *zonejs_packages_archives_dir
|
||||
destination: zone.js
|
||||
|
||||
# This job updates the content of repos like github.com/angular/core-builds
|
||||
# for every green build on angular/angular.
|
||||
publish_snapshot:
|
||||
executor: default-executor
|
||||
steps:
|
||||
# See below - ideally this job should not trigger for non-upstream builds.
|
||||
# But since it does, we have to check this condition.
|
||||
- run:
|
||||
name: Skip this job for Pull Requests and Fork builds
|
||||
# Note: Using `CIRCLE_*` env variables (instead of those defined in `env.sh` so that this
|
||||
# step can be run before `init_environment`.
|
||||
command: >
|
||||
if [[ -n "${CIRCLE_PR_NUMBER}" ]] ||
|
||||
[[ "$CIRCLE_PROJECT_USERNAME" != "angular" ]] ||
|
||||
[[ "$CIRCLE_PROJECT_REPONAME" != "angular" ]]; then
|
||||
circleci step halt
|
||||
fi
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
# CircleCI has a config setting to force SSH for all github connections
|
||||
# This is not compatible with our mechanism of using a Personal Access Token
|
||||
# Clear the global setting
|
||||
- run: git config --global --unset "url.ssh://git@github.com.insteadof"
|
||||
- run:
|
||||
name: Decrypt github credentials
|
||||
# We need ensure that the same default digest is used for encoding and decoding with
|
||||
# OpenSSL. OpenSSL versions might have different default digests which can cause
|
||||
# decryption failures based on the installed OpenSSL version. https://stackoverflow.com/a/39641378/4317734
|
||||
command: 'openssl aes-256-cbc -d -in .circleci/github_token -md md5 -k "${KEY}" -out ~/.git_credentials'
|
||||
- run: ./scripts/ci/publish-build-artifacts.sh
|
||||
|
||||
aio_monitoring_stable:
|
||||
executor: default-executor
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- install_chrome_libs
|
||||
- run: setPublicVar_CI_STABLE_BRANCH
|
||||
- run:
|
||||
name: Check out `aio/` and yarn from the stable branch
|
||||
command: |
|
||||
git fetch origin $CI_STABLE_BRANCH
|
||||
git checkout --force origin/$CI_STABLE_BRANCH -- aio/ .yarn/ .yarnrc
|
||||
# Ignore yarn's engines check, because we checked out `aio/package.json` from the stable
|
||||
# branch and there could be a node version skew, which is acceptable in this monitoring job.
|
||||
- run: yarn config set ignore-engines true
|
||||
- run:
|
||||
name: Run tests against https://angular.io/
|
||||
command: ./aio/scripts/test-production.sh https://angular.io/ $CI_AIO_MIN_PWA_SCORE
|
||||
- notify_webhook_on_fail:
|
||||
webhook_url_env_var: SLACK_CARETAKER_WEBHOOK_URL
|
||||
- notify_webhook_on_fail:
|
||||
webhook_url_env_var: SLACK_DEV_INFRA_CI_FAILURES_WEBHOOK_URL
|
||||
|
||||
aio_monitoring_next:
|
||||
executor: default-executor
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- install_chrome_libs
|
||||
- run:
|
||||
name: Run tests against https://next.angular.io/
|
||||
command: ./aio/scripts/test-production.sh https://next.angular.io/ $CI_AIO_MIN_PWA_SCORE
|
||||
- notify_webhook_on_fail:
|
||||
webhook_url_env_var: SLACK_CARETAKER_WEBHOOK_URL
|
||||
- notify_webhook_on_fail:
|
||||
webhook_url_env_var: SLACK_DEV_INFRA_CI_FAILURES_WEBHOOK_URL
|
||||
|
||||
legacy-unit-tests-saucelabs:
|
||||
executor:
|
||||
name: default-executor
|
||||
# In order to avoid the bottleneck of having a slow host machine, we acquire a better
|
||||
# container for this job. This is necessary because we launch a lot of browsers concurrently
|
||||
# and therefore the tunnel and Karma need to process a lot of file requests and tests.
|
||||
resource_class: xlarge
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
- init_saucelabs_environment
|
||||
- run:
|
||||
name: Starting Saucelabs tunnel service
|
||||
command: ./tools/saucelabs/sauce-service.sh run
|
||||
background: true
|
||||
- run: yarn tsc -p packages
|
||||
- run: yarn tsc -p modules
|
||||
- run: yarn bazel build //packages/zone.js:npm_package
|
||||
- run:
|
||||
# Waiting on ready ensures that we don't run tests too early without Saucelabs not being ready.
|
||||
name: Waiting for Saucelabs tunnel to connect
|
||||
command: ./tools/saucelabs/sauce-service.sh ready-wait
|
||||
- run:
|
||||
name: Running tests on Saucelabs.
|
||||
command: |
|
||||
browsers=$(node -e 'console.log(require("./browser-providers.conf").sauceAliases.CI_REQUIRED.join(","))')
|
||||
yarn karma start ./karma-js.conf.js --single-run --browsers=${browsers}
|
||||
- run:
|
||||
name: Stop Saucelabs tunnel service
|
||||
command: ./tools/saucelabs/sauce-service.sh stop
|
||||
|
||||
# Job that runs all unit tests of the `angular/components` repository.
|
||||
components-repo-unit-tests:
|
||||
executor:
|
||||
name: default-executor
|
||||
resource_class: xlarge
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
# Restore the cache before cloning the repository because the clone script re-uses
|
||||
# the restored repository if present. This reduces the amount of times the components
|
||||
# repository needs to be cloned (this is slow and increases based on commits in the repo).
|
||||
- restore_cache:
|
||||
keys:
|
||||
- *components_repo_unit_tests_cache_key
|
||||
# Whenever the `angular/components` SHA is updated, the cache key will no longer
|
||||
# match. The fallback cache will still match, and CircleCI will restore the most
|
||||
# recently cached repository folder. Without the fallback cache, we'd need to download
|
||||
# the repository from scratch and it would slow down the job. This is because we can't
|
||||
# clone the repository with reduced `--depth`, but rather need to clone the whole
|
||||
# repository to be able to support arbitrary SHAs.
|
||||
- *components_repo_unit_tests_cache_key_fallback
|
||||
- run:
|
||||
name: "Fetching angular/components repository"
|
||||
command: ./scripts/ci/clone_angular_components_repo.sh
|
||||
- run:
|
||||
# Run yarn install to fetch the Bazel binaries as used in the components repo.
|
||||
name: Installing dependencies.
|
||||
# TODO: remove this once the repo has been updated to use NodeJS v12 and Yarn 1.19.1.
|
||||
# We temporarily ignore the "engines" because the Angular components repository has
|
||||
# minimum dependency on NodeJS v12 and Yarn 1.19.1, but the framework repository uses
|
||||
# older versions.
|
||||
command: yarn --ignore-engines --cwd ${COMPONENTS_REPO_TMP_DIR} install --frozen-lockfile --non-interactive
|
||||
- save_cache:
|
||||
key: *components_repo_unit_tests_cache_key
|
||||
paths:
|
||||
# Temporary directory must be kept in sync with the `$COMPONENTS_REPO_TMP_DIR` env
|
||||
# variable. It needs to be hardcoded here, because env variables interpolation is
|
||||
# not supported.
|
||||
- "/tmp/angular-components-repo"
|
||||
- run:
|
||||
# Updates the `angular/components` `package.json` file to refer to the release output
|
||||
# inside the `packages-dist` directory. Note that it's not necessary to perform a yarn
|
||||
# install as Bazel runs Yarn automatically when needed.
|
||||
name: Setting up release packages.
|
||||
command: node scripts/ci/update-deps-to-dist-packages.js ${COMPONENTS_REPO_TMP_DIR}/package.json dist/packages-dist/
|
||||
- run:
|
||||
name: "Running `angular/components` unit tests"
|
||||
command: ./scripts/ci/run_angular_components_unit_tests.sh
|
||||
|
||||
test_zonejs:
|
||||
executor:
|
||||
name: default-executor
|
||||
resource_class: xlarge
|
||||
steps:
|
||||
- custom_attach_workspace
|
||||
- init_environment
|
||||
# Install
|
||||
- run: yarn --cwd packages/zone.js install --frozen-lockfile --non-interactive
|
||||
# Run zone.js tools tests
|
||||
- run: yarn --cwd packages/zone.js promisetest
|
||||
- run: yarn --cwd packages/zone.js promisefinallytest
|
||||
- run: yarn bazel build //packages/zone.js:npm_package &&
|
||||
cp dist/bin/packages/zone.js/npm_package/bundles/zone-mix.umd.js ./packages/zone.js/test/extra/ &&
|
||||
cp dist/bin/packages/zone.js/npm_package/bundles/zone-patch-electron.umd.js ./packages/zone.js/test/extra/ &&
|
||||
yarn --cwd packages/zone.js electrontest
|
||||
- run: yarn --cwd packages/zone.js jesttest
|
||||
|
||||
# Windows jobs
|
||||
# Docs: https://circleci.com/docs/2.0/hello-world-windows/
|
||||
test_win:
|
||||
executor: windows-executor
|
||||
steps:
|
||||
- setup_win
|
||||
- run:
|
||||
# Ran into a command parsing problem where `-browser:chromium-local` was converted to
|
||||
# `-browser: chromium-local` (a space was added) in https://circleci.com/gh/angular/angular/357511.
|
||||
# Probably a powershell command parsing thing. There's no problem using a yarn script though.
|
||||
command: yarn circleci-win-ve
|
||||
no_output_timeout: 45m
|
||||
# Save bazel repository cache to use on subsequent runs.
|
||||
# We don't save node_modules because it's faster to use the linux workspace and reinstall.
|
||||
- save_cache:
|
||||
key: *cache_key_win
|
||||
paths:
|
||||
- "C:/Users/circleci/bazel_repository_cache"
|
||||
|
||||
test_ivy_aot_win:
|
||||
executor: windows-executor
|
||||
steps:
|
||||
- setup_win
|
||||
- run:
|
||||
command: yarn circleci-win-ivy
|
||||
no_output_timeout: 45m
|
||||
|
||||
|
||||
workflows:
|
||||
version: 2
|
||||
@ -775,21 +381,9 @@ workflows:
|
||||
- lint:
|
||||
requires:
|
||||
- setup
|
||||
- test:
|
||||
requires:
|
||||
- setup
|
||||
- test_ivy_aot:
|
||||
requires:
|
||||
- setup
|
||||
- build-npm-packages:
|
||||
requires:
|
||||
- setup
|
||||
- build-ivy-npm-packages:
|
||||
requires:
|
||||
- setup
|
||||
- legacy-unit-tests-saucelabs:
|
||||
requires:
|
||||
- setup
|
||||
- test_aio:
|
||||
requires:
|
||||
- setup
|
||||
@ -799,22 +393,9 @@ workflows:
|
||||
- test_aio_local:
|
||||
requires:
|
||||
- build-npm-packages
|
||||
- test_aio_local:
|
||||
name: test_aio_local_viewengine
|
||||
viewengine: true
|
||||
requires:
|
||||
- build-npm-packages
|
||||
- test_aio_tools:
|
||||
requires:
|
||||
- build-npm-packages
|
||||
- test_docs_examples:
|
||||
requires:
|
||||
- build-npm-packages
|
||||
- test_docs_examples:
|
||||
name: test_docs_examples_viewengine
|
||||
viewengine: true
|
||||
requires:
|
||||
- build-npm-packages
|
||||
- aio_preview:
|
||||
# Only run on PR builds. (There can be no previews for non-PR builds.)
|
||||
<<: *only_on_pull_requests
|
||||
@ -823,78 +404,3 @@ workflows:
|
||||
- test_aio_preview:
|
||||
requires:
|
||||
- aio_preview
|
||||
- publish_packages_as_artifacts:
|
||||
requires:
|
||||
- build-npm-packages
|
||||
- publish_snapshot:
|
||||
# Note: no filters on this job because we want it to run for all upstream branches
|
||||
# We'd really like to filter out pull requests here, but not yet available:
|
||||
# https://discuss.circleci.com/t/workflows-pull-request-filter/14396/4
|
||||
# Instead, the job just exits immediately at the first step.
|
||||
requires:
|
||||
# Only publish if tests and integration tests pass
|
||||
- test
|
||||
- test_ivy_aot
|
||||
# Only publish if `aio`/`docs` tests using the locally built Angular packages pass
|
||||
- test_aio_local
|
||||
- test_aio_local_viewengine
|
||||
- test_docs_examples
|
||||
- test_docs_examples_viewengine
|
||||
# Get the artifacts to publish from the build-packages-dist job
|
||||
# since the publishing script expects the legacy outputs layout.
|
||||
- build-npm-packages
|
||||
- build-ivy-npm-packages
|
||||
- legacy-unit-tests-saucelabs
|
||||
- components-repo-unit-tests:
|
||||
requires:
|
||||
- build-npm-packages
|
||||
- test_zonejs:
|
||||
requires:
|
||||
- setup
|
||||
# Windows Jobs
|
||||
# These are very slow so we run them on non-PRs only for now.
|
||||
# TODO: remove the filter when CircleCI makes Windows FS faster.
|
||||
# The Windows jobs are only run after their non-windows counterparts finish successfully.
|
||||
# This isn't strictly necessary as there is no artifact dependency, but helps economize
|
||||
# CI resources by not attempting to build when we know should fail.
|
||||
- test_win:
|
||||
<<: *skip_on_pull_requests
|
||||
requires:
|
||||
- test
|
||||
- test_ivy_aot_win:
|
||||
<<: *skip_on_pull_requests
|
||||
requires:
|
||||
- test_ivy_aot
|
||||
|
||||
monitoring:
|
||||
jobs:
|
||||
- setup
|
||||
- aio_monitoring_stable:
|
||||
requires:
|
||||
- setup
|
||||
- aio_monitoring_next:
|
||||
requires:
|
||||
- setup
|
||||
- saucelabs_ivy:
|
||||
# Testing saucelabs via Bazel currently taking longer than the legacy saucelabs job as it
|
||||
# each karma_web_test target is provisioning and tearing down browsers which is adding
|
||||
# a lot of overhead. Running once daily on master only to avoid wasting resources and
|
||||
# slowing down CI for PRs.
|
||||
# TODO: Run this job on all branches (including PRs) once karma_web_test targets can
|
||||
# share provisioned browsers and we can remove the legacy saucelabs job.
|
||||
requires:
|
||||
- setup
|
||||
- saucelabs_view_engine:
|
||||
# Testing saucelabs via Bazel currently taking longer than the legacy saucelabs job as it
|
||||
# each karma_web_test target is provisioning and tearing down browsers which is adding
|
||||
# a lot of overhead. Running once daily on master only to avoid wasting resources and
|
||||
# slowing down CI for PRs.
|
||||
# TODO: Run this job on all branches (including PRs) once karma_web_test targets can
|
||||
# share provisioned browsers and we can remove the legacy saucelabs job.
|
||||
requires:
|
||||
- setup
|
||||
triggers:
|
||||
- schedule:
|
||||
<<: *only_on_master
|
||||
# Runs monitoring jobs at 10:00AM every day.
|
||||
cron: "0 10 * * *"
|
||||
|
@ -17,7 +17,7 @@ echo "source $envHelpersPath;" >> $BASH_ENV;
|
||||
####################################################################################################
|
||||
setPublicVar CI "$CI"
|
||||
setPublicVar PROJECT_ROOT "$projectDir";
|
||||
setPublicVar CI_AIO_MIN_PWA_SCORE "95";
|
||||
setPublicVar CI_AIO_MIN_PWA_SCORE "62";
|
||||
# This is the branch being built; e.g. `pull/12345` for PR builds.
|
||||
setPublicVar CI_BRANCH "$CIRCLE_BRANCH";
|
||||
setPublicVar CI_BUILD_URL "$CIRCLE_BUILD_URL";
|
||||
|
18
.github/PULL_REQUEST_TEMPLATE.md
vendored
18
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -1,12 +1,12 @@
|
||||
## Lista de Verificación del PR
|
||||
Comprueba si tu PR cumple los siguientes requisitos:
|
||||
|
||||
- [ ] El mensaje de commit conforme con [nuestras reglas](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#commit)
|
||||
- [ ] Prueba los cambios que agregaste (arreglo de bugs / funcionalidades)
|
||||
- [ ] Revisa tus traducciones o cambios de contenido
|
||||
- [ ] Consulté el [diccionario de términos](https://github.com/angular-hispano/angular/issues/9) en español
|
||||
- [ ] Se han creado dos archivos con la extensión correspondiente(.en.md para el archivo en inglés y .md para el Archivo en español)
|
||||
- [ ] PR enlazada con el issue correspondiente
|
||||
- [ ] El mensaje de commit esta conforme con [nuestras reglas](https://github.com/angular-hispano/angular/blob/master/CONTRIBUTING.md#-formato-para-el-mensaje-de-los-commits)
|
||||
- [ ] Probe los cambios que agregué (arreglo de bugs / funcionalidades)
|
||||
- [ ] Revisé previamente las traducciones o cambios de contenido
|
||||
- [ ] Consulté el [diccionario de términos](https://github.com/angular-hispano/angular/blob/master/aio/diccionario-de-términos.md) en español
|
||||
- [ ] He creado dos archivos con la extensión correspondiente(.en.md para el archivo en inglés y .md para el Archivo en español)
|
||||
- [ ] He enlazado el commit con el issue correspondiente <!-- ejemplo Fixes #X -->
|
||||
|
||||
|
||||
## Tipo de PR
|
||||
@ -16,13 +16,13 @@ Comprueba si tu PR cumple los siguientes requisitos:
|
||||
|
||||
- [ ] Bugfix
|
||||
- [ ] Funcionalidad
|
||||
- [ ] Actualizar el estilo del código (formato, variables locales)
|
||||
- [ ] Actualización de el estilo del código (formato, variables locales)
|
||||
- [ ] Refactorización (no cambios en la funcionalidad, no cambios en el api)
|
||||
- [ ] Cambios relacionados al build
|
||||
- [ ] Cambios relacionados al CI (Integración continua)
|
||||
- [ ] Cambios en el contenido de la documentación
|
||||
- [ ] Cambios en la aplicación / infrastructura de angular.io
|
||||
- [ ] Otro... Por favor describela:
|
||||
- [ ] Cambios en la aplicación / infraestructura de angular.io
|
||||
- [ ] Otro... Por favor describe la:
|
||||
|
||||
## ¿Cuál es el comportamiento actual?
|
||||
<!-- Describe el comportamiento actual que está modificando o vincule a un problema relevante.
|
||||
|
@ -1,12 +1,72 @@
|
||||
# Contributor Code of Conduct
|
||||
## Version 0.3b-angular
|
||||
# Código de Conducta
|
||||
|
||||
As contributors and maintainers of the Angular project, we pledge to respect everyone who contributes by posting issues, updating documentation, submitting pull requests, providing feedback in comments, and any other activities.
|
||||
## 1. Propósito
|
||||
|
||||
Communication through any of Angular's channels (GitHub, Gitter, IRC, mailing lists, Google+, Twitter, etc.) must be constructive and never resort to personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
|
||||
“Prometemos brindar cortesía y respeto a cualquier persona involucrada en esta comunidad, sin importar el género con el que se identifique, su orientación sexual, limitación física, edad, raza, etnia, religión o nivel de conocimiento. Esperamos que cualquiera que desee contribuir en este proyecto brinde el mismo comportamiento”
|
||||
|
||||
We promise to extend courtesy and respect to everyone involved in this project regardless of gender, gender identity, sexual orientation, disability, age, race, ethnicity, religion, or level of experience. We expect anyone contributing to the Angular project to do the same.
|
||||
Bajo ese principio queremos enfocar esta comunidad, una comunidad de respeto por el otro, donde cualquiera que sienta pasión por Angular y desee involucrarse con cualquier tipo de actividad deberá ayudar a mantener una atmósfera de cortesía por el otro, respetando los pensamientos, acciones, ideales y propuestas del otro.
|
||||
|
||||
If any member of the community violates this code of conduct, the maintainers of the Angular project may take action, removing issues, comments, and PRs or blocking accounts as deemed appropriate.
|
||||
## 2. Comportamiento esperado
|
||||
|
||||
If you are subject to or witness unacceptable behavior, or have any other concerns, please email us at [conduct@angular.io](mailto:conduct@angular.io).
|
||||
- Evitar usar expresiones o gestos insultantes, humillantes o intimidatorios para referirnos a otros.
|
||||
- Ejercita la consideración y el respeto en tus comunicaciones y acciones.
|
||||
- Absténte de adoptar una conducta y un lenguaje degradantes, discriminatorios, abusivos o acosadores.
|
||||
- Evitar comportamientos que agredan las expresiones de identidad, género, creencias religiosas, acciones que lastimen o los aíslen a otros.
|
||||
- Evitar comentarios sobre ideas políticas.
|
||||
- No se toleran conductas físicas y actitudes dirigidas al descrédito personal, físico o emocional de cualquier persona.
|
||||
- No se toleran chistes y comentarios excluyentes, sexistas y racistas.
|
||||
- Se rechaza actitudes de hostigamiento.
|
||||
- Se rechaza el acoso: este se entiende como cualquier tipo de comentario verbal que refuerce discriminación por género, identidad y expresión de género, orientación sexual, discapacidad, apariencia física, tamaño corporal, raza, edad o religión en contextos laborales o sociales.
|
||||
- No se tolera el contacto físico y/o la atención sexual no deseada.
|
||||
- Promover la igualdad de oportunidades de formación, educación, intercambio y retroalimentación antes, durante y después de los eventos.
|
||||
- Intenta colaborar en lugar de generar conflicto.
|
||||
- Sé consciente de tu entorno y de tus compañeros participantes. Alerta a líderes de la comunidad si notas una situación peligrosa, alguien en apuros, o violaciones de este Código de Conducta, incluso si parecen intrascendentes.
|
||||
|
||||
## 3. Comportamiento inaceptable
|
||||
Comportamientos inaceptables incluyen: intimidación, acoso, abuso, discriminación, comunicación despectiva o degradante o acciones por cualquier participante en nuestra comunidad ya sea virtual, o en las comunicaciones uno-a-uno que se realizan en el contexto de la comunidad. Por favor ser respetuoso con todos.
|
||||
|
||||
El acoso incluye: comentarios nocivos o perjudiciales, verbales o escritos relacionados con el género, la orientación sexual, raza, religión, discapacidad; uso inadecuado de desnudos y / o imágenes sexuales en espacios públicos (incluyendo la presentación diapositivas); intimidación deliberada, acecho o seguimiento; fotografías o grabaciones acosadoras; interrupción sostenida de charlas y otros eventos; contacto físico inapropiado, y atención sexual no deseada.
|
||||
|
||||
## 4. Consecuencias de comportamiento inaceptable
|
||||
Se espera que personas a quienes se les solicite que detengan su comportamiento inaceptable lo hagan de manera inmediata esto será válido para cualquier miembro de la comunidad.
|
||||
|
||||
En caso de presentarse una violación al código de conducta de manera repetida se tendrá cero tolerancia a este comportamiento por parte de los organizadores.
|
||||
|
||||
Si un miembro de la comunidad participa en una conducta inaceptable, los organizadores pueden tomar cualquier acción que consideren apropiada, hasta e incluyendo una prohibición temporal o expulsión permanente de la comunidad, sin previo aviso.
|
||||
|
||||
Priorizamos la seguridad de las personas marginadas sobre la comodidad de las personas privilegiadas. Nos reservamos el derecho de no actuar sobre las quejas relacionadas con:
|
||||
|
||||
- El "racismo inverso", "sexismo inverso" y "cisfobia".
|
||||
- Comunicación razonable de límites, como "déjame en paz", "vete" o "no estoy discutiendo esto contigo".
|
||||
- Al comunicarse en un "tono", no se encuentra agradable.
|
||||
- Identificando comportamientos o suposiciones racistas, sexistas, cissexistas u opresivas.
|
||||
|
||||
## 5. ¿Qué hacer si se incumple el código de conducta?
|
||||
Si eres víctima o testigo de una conducta inaceptable, o tienes cualquier inquietud, por favor comunícate con el equipo organizador lo antes posible:
|
||||
|
||||
- Mensaje directo: Michael Prentice (@splaktar)
|
||||
- Mensaje directo: Jorge Cano (@jorgeucano)
|
||||
- Mensaje directo: Andrés Villanueva (@villanuevand)
|
||||
- Email: [soporte@angular.lat](mailto:soporte@angular.lat)
|
||||
|
||||
### ¿Qué pasa después?
|
||||
- Una vez haya sido notificada el no cumplimiento de la norma, el equipo de liderazgo se reunirán y analizarán el caso.
|
||||
- Los incidentes presentados se manejarán con discreción.
|
||||
- Los organizadores se comunicarán con la persona que incumplió la norma y tomarán las medidas respectivas.
|
||||
- Se realizará un acompañamiento a la persona agredida y se apoyará.
|
||||
- Si el incidente se hace público, Angular Hispano no se hace responsable de los perjuicios que esto pueda ocasionar en el agresor o el agredido.
|
||||
|
||||
## 6. Alcance
|
||||
Esperamos que todos los participantes de la comunidad (organizadores, voluntarios, contribuyentes pagados o de otro modo; patrocinadores; y otros invitados) se atengan a este Código de Conducta en todos los espacios virtuales y presenciales, así como en todas las comunicaciones de uno-a-uno pertinentes la comunidad.
|
||||
|
||||
### Colaboradores
|
||||
|
||||
- Alejandra Giraldo
|
||||
- Vanessa Marely
|
||||
- Mariano Alvarez
|
||||
- Andrés Villanueva
|
||||
- Michael Prentice
|
||||
- javascript&friends
|
||||
- Angular
|
||||
- She Codes Angular
|
||||
- Colombia dev
|
@ -7,7 +7,7 @@ Como colaborador, estos son los lineamientos que nos gustaría que siguieras:
|
||||
- [¿Preguntas o problemas?](#question)
|
||||
- [_Issues_ y _bugs_](#issue)
|
||||
- [Solicitud de funcionalidades](#feature)
|
||||
- [Lineamientos para la creación de _issues_ y _PR_](#submit)
|
||||
- [Guía para la creación de issues y PRs](#submit)
|
||||
- [Reglas del código](#rules)
|
||||
- [Convención para el mensaje de los _commits_](#commit)
|
||||
- [Firma del Acuerdo de Licencia de Colaborador (CLA)](#cla)
|
||||
@ -53,7 +53,7 @@ Si deseas implementar una nueva funcionalidad, por favor considera el tamaño de
|
||||
* **Cambios pequeños** pueden ser elaborados y directamente [creados como un _pull request_](#submit-pr).
|
||||
|
||||
|
||||
## <a name="submit"></a> Lineamientos para la creación de _issues_ y _pull requests_
|
||||
## <a name="submit"></a> Guía para la creación de issues y PRs
|
||||
|
||||
|
||||
### <a name="submit-issue"></a> Creación de _issues_
|
||||
@ -307,7 +307,7 @@ CAMBIO SIGNIFICATIVO: <resumen del cambio significativo>
|
||||
<descripción del cambio significativo + instrucciones para la migración>
|
||||
<LINEA VACIA>
|
||||
<LINEA VACIA>
|
||||
Soluciona #<issue número>
|
||||
Fix #<issue número>
|
||||
```
|
||||
|
||||
La sección de cambios significativos debería comenzar con la frase "CAMBIO SIGNIFICATIVO: " seguido de un resumen del cambio significativo, una línea en blanco y una descripción detallada del cambio significativo que también incluya instrucciones de migración.
|
||||
@ -325,13 +325,7 @@ El contenido del mensaje del commit debería contener:
|
||||
|
||||
## <a name="cla"></a> Firma del Acuerdo de Licencia de Colaborador (CLA)
|
||||
|
||||
Por favor firma nuestro Acuerdo de Licencia de Colaborador (CLA) antes de crear _pull requests_. Para que cualquier cambio de código sea aceptado, el Acuerdo de Licencia de Colaborador (CLA) debe ser firmado. ¡Es un proceso rápido, lo prometemos!
|
||||
|
||||
* Para las personas, tenemos un [formulario simple][individual-cla].
|
||||
* Para corporaciones, necesitaremos que
|
||||
[impriman, firmen, escaneen y envíen por email, fax o correo el formulario][corporate-cla].
|
||||
|
||||
Si tiene más de una cuenta de GitHub o varias direcciones de correo electrónico asociadas con una sola cuenta de GitHub, debes firmar el CLA utilizando la dirección de correo electrónico principal de la cuenta de GitHub utilizada para crear los commits de Git y la creación de PRs.
|
||||
Por favor firma nuestro Acuerdo de Licencia de Colaborador (CLA) cuando creas tu primer pull request. Para que cualquier cambio de código sea aceptado, el Acuerdo de Licencia de Colaborador (CLA) debe ser firmado. Es un proceso rápido con nuestro CLA assistant que está integrado con nuestro CI.
|
||||
|
||||
Los siguientes documentos pueden ayudarte a resolver problemas con cuentas de GitHub y múltiples direcciones de correo electrónico:
|
||||
|
||||
|
26
README.en.md
Normal file
26
README.en.md
Normal file
@ -0,0 +1,26 @@
|
||||
[](https://circleci.com/gh/angular/workflows/angular/tree/master)
|
||||
[](https://gitter.im/angular/angular?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](https://www.npmjs.com/@angular/core)
|
||||
|
||||
|
||||
# Angular
|
||||
|
||||
Angular is a development platform for building mobile and desktop web applications using TypeScript/JavaScript and other languages.
|
||||
|
||||
## Quickstart
|
||||
|
||||
[Get started in 5 minutes][quickstart].
|
||||
|
||||
## Changelog
|
||||
|
||||
[Learn about the latest improvements][changelog].
|
||||
|
||||
## Want to help?
|
||||
|
||||
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on our
|
||||
guidelines for [contributing][contributing] and then check out one of our issues in the [hotlist: community-help](https://github.com/angular/angular/labels/hotlist%3A%20community-help).
|
||||
|
||||
[contributing]: https://github.com/angular/angular/blob/master/CONTRIBUTING.md
|
||||
[quickstart]: https://angular.io/start
|
||||
[changelog]: https://github.com/angular/angular/blob/master/CHANGELOG.md
|
||||
[ng]: https://angular.io
|
40
README.md
40
README.md
@ -1,25 +1,25 @@
|
||||
[](https://circleci.com/gh/angular/workflows/angular/tree/master)
|
||||
[](https://gitter.im/angular/angular?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](https://www.npmjs.com/@angular/core)
|
||||
# Angular en español
|
||||
|
||||
|
||||
# Angular
|
||||
|
||||
Angular es una plataforma de desarrollo para construir aplicaciones web y móviles que usa TypeScript/JavaScript y otros lenguajes de programación.
|
||||
|
||||
## Guía rápida
|
||||
|
||||
[Comienza a usarlo en 5 minutos][quickstart].
|
||||
|
||||
## Registro de cambios (Changelog)
|
||||
|
||||
[Últimas mejoras realizadas][changelog].
|
||||
Angular es una plataforma de desarrollo para construir aplicaciones web y móviles que usa
|
||||
TypeScript/JavaScript y otros lenguajes de programación.
|
||||
|
||||
## ¿Quieres ayudar?
|
||||
|
||||
¿Quieres encontrar fallos, colaborar con código, o mejorar la documentación? ¡Excelente! Lee nuestras
|
||||
pautas para [colaborar][contributing] y luego revisa algunos de nuestras incidencias (issues) en [ayuda comunitaria](https://github.com/angular-hispano/angular/labels/ayuda%20comunitaria).
|
||||
### Documentación en español
|
||||
|
||||
[contributing]: https://github.com/angular-hispano/angular/blob/master/CONTRIBUTING.md
|
||||
[quickstart]: https://docs.angular.lat/start
|
||||
[changelog]: https://github.com/angular/angular/blob/master/CHANGELOG.md
|
||||
¿Quieres mejorar la documentación? ¡Excelente! Lee nuestras pautas para
|
||||
[colaborar](CONTRIBUTING.md) y luego revisa algunos de nuestras
|
||||
[issues](https://github.com/angular-hispano/angular/issues).
|
||||
|
||||
### El framework
|
||||
|
||||
La colaboración para corregir errores y agregar funciones en el framework debe realizarse en inglés a través
|
||||
del repositorio [angular/angular](https://github.com/angular/angular) upstream.
|
||||
|
||||
## Guía rápida
|
||||
|
||||
[Comienza a usarlo en 5 minutos](https://docs.angular.lat/start).
|
||||
|
||||
## Registro de cambios (Changelog)
|
||||
|
||||
[Últimas mejoras realizadas](CHANGELOG.md).
|
||||
|
167
aio/README.md
167
aio/README.md
@ -1,140 +1,131 @@
|
||||
# Angular documentation project (https://angular.io)
|
||||
# Proyecto de documentación Angular (https://docs.angular.lat)
|
||||
|
||||
Everything in this folder is part of the documentation project. This includes
|
||||
Todo en esta carpeta es parte del proyecto de documentación. Esto incluye:
|
||||
|
||||
* the web site for displaying the documentation
|
||||
* the dgeni configuration for converting source files to rendered files that can be viewed in the web site.
|
||||
* the tooling for setting up examples for development; and generating live-example and zip files from the examples.
|
||||
* El sitio web para mostrar la documentación
|
||||
* La configuración de dgeni para convertir los archivos de origen a archivos renderizados que se pueden vizualizar en el sitio web.
|
||||
* Las herramientas para establecer ejemplos para el desarrollo; y generar archivos en tiempo real y archivos zip desde los ejemplos.
|
||||
|
||||
## Developer tasks
|
||||
## Tareas de desarrollador
|
||||
|
||||
We use [Yarn](https://yarnpkg.com) to manage the dependencies and to run build tasks.
|
||||
You should run all these tasks from the `angular/aio` folder.
|
||||
Here are the most important tasks you might need to use:
|
||||
Nosotros usamos [Yarn](https://yarnpkg.com) para gestionar las dependencias y crear tareas de compilación.
|
||||
Debes ejecutar todas estas tareas desde la carpeta `angular/aio`.
|
||||
Aquí están las tareas más importantes que podrías necesitar usar:
|
||||
|
||||
* `yarn` - install all the dependencies.
|
||||
* `yarn setup` - install all the dependencies, boilerplate, stackblitz, zips and run dgeni on the docs.
|
||||
* `yarn setup-local` - same as `setup`, but build the Angular packages from the source code and use these locally built versions (instead of the ones fetched from npm) for aio and docs examples boilerplate.
|
||||
* `yarn` - instalar todas las dependencias.
|
||||
* `yarn setup` - instalar todas las dependencias, boilerplate, stackblitz, zips y ejecuta dgeni en los documentos.
|
||||
* `yarn setup-local` - igual que `setup`, pero crea los paquetes de Angular a partir del código y usa estas versiones construidas localmente (en lugar de las recuperadas desde npm) para aio y ejemplos de documentos boilerplate.
|
||||
|
||||
* `yarn build` - create a production build of the application (after installing dependencies, boilerplate, etc).
|
||||
* `yarn build-local` - same as `build`, but use `setup-local` instead of `setup`.
|
||||
* `yarn build-local-with-viewengine` - same as `build-local`, but in addition also turns on `ViewEngine` (pre-Ivy) mode in aio.
|
||||
(Note: To turn on `ViewEngine` mode in docs examples, see `yarn boilerplate:add:viewengine` below.)
|
||||
* `yarn build` - crear una compilación de producción de la aplicación (después de instalar dependencias, boilerplate, etc).
|
||||
* `yarn build-local` - igual que `build`, pero usa `setup-local` en lugar de `setup`.
|
||||
* `yarn build-local-with-viewengine` - igual que `build-local`, pero además también enciende el modo `ViewEngine` (pre-Ivy) en aio.
|
||||
(Nota: Encender el modo `ViewEngine` en ejemplos de documentos, ver `yarn boilerplate:add:viewengine` abajo.)
|
||||
|
||||
* `yarn start` - run a development web server that watches the files; then builds the doc-viewer and reloads the page, as necessary.
|
||||
* `yarn serve-and-sync` - run both the `docs-watch` and `start` in the same console.
|
||||
* `yarn lint` - check that the doc-viewer code follows our style rules.
|
||||
* `yarn test` - watch all the source files, for the doc-viewer, and run all the unit tests when any change.
|
||||
* `yarn test --watch=false` - run all the unit tests once.
|
||||
* `yarn e2e` - run all the e2e tests for the doc-viewer.
|
||||
* `yarn start` - ejecutar un servidor web de desarrollo que observa los archivos; luego crea el doc-viewer y vuelve a cargar la página, según sea necesario.
|
||||
* `yarn serve-and-sync` - ejecutar ambos, el `docs-watch` y `start` en la misma consola.
|
||||
* `yarn lint` - comprobar que el código del doc-viewer sigue nuestras reglas de estilo.
|
||||
* `yarn test` - observar todos los archivos de origen, para el doc-viewer, y ejecuta todas las pruebas unitarias cuando haya algún cambio.
|
||||
* `yarn test --watch=false` -ejecutar todas las pruebas unitarias una sola vez.
|
||||
* `yarn e2e` - ejecutar todas las pruebas de e2e para el doc-viewer.
|
||||
|
||||
* `yarn docs` - generate all the docs from the source files.
|
||||
* `yarn docs-watch` - watch the Angular source and the docs files and run a short-circuited doc-gen for the docs that changed.
|
||||
* `yarn docs-lint` - check that the doc gen code follows our style rules.
|
||||
* `yarn docs-test` - run the unit tests for the doc generation code.
|
||||
* `yarn docs` - generar toda la documentación desde los archivos fuente.
|
||||
* `yarn docs-watch` - observar el código Angular, los archivos de documentación y ejecutar un 'doc-gen' en corto circuito para los documentos que fueron cambiados.
|
||||
* `yarn docs-lint` - comprobar que el código del documento generado sigue nuestras reglas de estilo.
|
||||
* `yarn docs-test` - ejecutar las pruebas unitarias para el código de generación de doc.
|
||||
|
||||
* `yarn boilerplate:add` - generate all the boilerplate code for the examples, so that they can be run locally.
|
||||
* `yarn boilerplate:add:viewengine` - same as `boilerplate:add` but also turns on `ViewEngine` (pre-Ivy) mode.
|
||||
* `yarn boilerplate:add` - generar todo el código boilerplate para los ejemplos, para que puedan ejecutarse localmente.
|
||||
* `yarn boilerplate:add:viewengine` - igual que `boilerplate:add` pero también enciende el modo `ViewEngine` (pre-Ivy).
|
||||
|
||||
* `yarn boilerplate:remove` - remove all the boilerplate code that was added via `yarn boilerplate:add`.
|
||||
* `yarn generate-stackblitz` - generate the stackblitz files that are used by the `live-example` tags in the docs.
|
||||
* `yarn generate-zips` - generate the zip files from the examples. Zip available via the `live-example` tags in the docs.
|
||||
* `yarn boilerplate:remove` - eliminar todo el código boilerplate que fue añadido a través`yarn boilerplate:add`.
|
||||
* `yarn generate-stackblitz` - generar los archivos stackblitz que están usados por la etiqueta `live-example` en documentos.
|
||||
* `yarn generate-zips` - generar los archivos zip desde los ejemplos. Zip está disponible a través de la etiqueta `live-example` en los documentos.
|
||||
|
||||
* `yarn example-e2e` - run all e2e tests for examples. Available options:
|
||||
- `--setup`: generate boilerplate, force webdriver update & other setup, then run tests.
|
||||
- `--local`: run e2e tests with the local version of Angular contained in the "dist" folder.
|
||||
_Requires `--setup` in order to take effect._
|
||||
- `--viewengine`: run e2e tests in `ViewEngine` (pre-Ivy) mode.
|
||||
- `--filter=foo`: limit e2e tests to those containing the word "foo".
|
||||
* `yarn example-e2e` - ejecutar todas las pruebas e2e para ejemplos. Opciones disponibles:
|
||||
- `--setup`: generar boilerplate, forzar la actualización del controlador web y otras configuraciones, luego ejecutar las pruebas.
|
||||
- `--local`: ejecutar pruebas e2e con la versión local de Angular contenida en la carpeta "dist".
|
||||
_Requiere `--setup` para que surta efecto._
|
||||
- `--viewengine`: ejecutar pruebas e2e en modo `ViewEngine` (pre-Ivy).
|
||||
- `--filter=foo`: limitar pruebas e2e a las que contienen la palabra "foo".
|
||||
|
||||
> **Note for Windows users**
|
||||
> **Nota para usuarios Windows**
|
||||
>
|
||||
> Setting up the examples involves creating some [symbolic links](https://en.wikipedia.org/wiki/Symbolic_link) (see [here](./tools/examples/README.md#symlinked-node_modules) for details). On Windows, this requires to either have [Developer Mode enabled](https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10) (supported on Windows 10 or newer) or run the setup commands as administrator.
|
||||
> Configurar los ejemplos implica crear algunos [enlaces simbólicos](https://es.wikipedia.org/wiki/Enlace_simb%C3%B3lico) (ver [Aquí](./tools/examples/README.md#symlinked-node_modules) para más detalles). En Windows, esto requiere tener [Habilitado el Modo de desarrollador ](https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10) (compatible con Windows 10 o más reciente) o ejecutar los comandos de configuración cómo administrador.
|
||||
>
|
||||
> The affected commands are:
|
||||
> Los comandos afectados son:
|
||||
> - `yarn setup` / `yarn setup-*`
|
||||
> - `yarn build` / `yarn build-*`
|
||||
> - `yarn boilerplate:add`
|
||||
> - `yarn example-e2e --setup`
|
||||
|
||||
## Using ServiceWorker locally
|
||||
## Usando ServiceWorker localmente
|
||||
|
||||
Running `yarn start` (even when explicitly targeting production mode) does not set up the
|
||||
ServiceWorker. If you want to test the ServiceWorker locally, you can use `yarn build` and then
|
||||
serve the files in `dist/` with `yarn http-server dist -p 4200`.
|
||||
Ejecutando `yarn start` (incluso cuando se apunta explícitamente al modo de producción) no configura el
|
||||
ServiceWorker. Si quieres probar el ServiceWorker localmente, puedes usar `yarn build` y luego
|
||||
ejecutar los archivos en `dist/` con `yarn http-server dist -p 4200`.
|
||||
|
||||
|
||||
## Guide to authoring
|
||||
## Guía de autoría
|
||||
Existen dos tipos de contenido en la documentación:
|
||||
|
||||
There are two types of content in the documentation:
|
||||
* **Documentación de API**: descripciones de los módulos, clases, interfaces, decoradores, etc que son parte de la plataforma Angular.
|
||||
La documentacion de API está generada directamente desde el código fuente.
|
||||
El código fuente está contenido en archivos TypeScript , almacenados en la carpeta `angular/packages`.
|
||||
Cada elemento de la API puede tener un comentario anterior, el cual contiene etiquetas y contenido de estilos JSDoc.
|
||||
El contenido está escrito en markdown.
|
||||
|
||||
* **API docs**: descriptions of the modules, classes, interfaces, decorators, etc that make up the Angular platform.
|
||||
API docs are generated directly from the source code.
|
||||
The source code is contained in TypeScript files, located in the `angular/packages` folder.
|
||||
Each API item may have a preceding comment, which contains JSDoc style tags and content.
|
||||
The content is written in markdown.
|
||||
* **Otro contenido**: guias, tutoriales, y otro material de marketing.
|
||||
Todos los demás contenidos se escriben utilizando markdown en archivos de texto, ubicados en la carpeta `angular/aio/content`.
|
||||
Más específicamente, hay subcarpetas que contienen tipos particulares de contenido: guías, tutoriales y marketing.
|
||||
|
||||
* **Other content**: guides, tutorials, and other marketing material.
|
||||
All other content is written using markdown in text files, located in the `angular/aio/content` folder.
|
||||
More specifically, there are sub-folders that contain particular types of content: guides, tutorial and marketing.
|
||||
* **Ejempos de código**: los ejemplos de código deben ser comprobables para garantizar su precisión.
|
||||
Además, nuestros ejemplos tienen un aspecto específico y permiten al usuario copiar el código fuente. Para mayor
|
||||
ejemplos se representan en una interfaz con pestañas (e.g. template, HTML, y TypeScript en pestañas separadas). Adicionalmente, algunos son ejemplos en acción, que proporcionan enlaces donde se puede editar el código, ejecutar, y/o descargar. Para obtener más detalles sobre cómo trabajar con ejemplos de código, lea los [fragmentos de código](https://docs.angular.lat/guide/docs-style-guide#code-snippets), [código fuente de marcado ](https://docs.angular.lat/guide/docs-style-guide#source-code-markup), y [ ejemplos en acción ](https://docs.angular.lat/guide/docs-style-guide#live-examples) paginas de los [ autores de guías de estilo ](https://docs.angular.lat/guide/docs-style-guide).
|
||||
|
||||
* **Code examples**: code examples need to be testable to ensure their accuracy.
|
||||
Also, our examples have a specific look and feel and allow the user to copy the source code. For larger
|
||||
examples they are rendered in a tabbed interface (e.g. template, HTML, and TypeScript on separate
|
||||
tabs). Additionally, some are live examples, which provide links where the code can be edited, executed, and/or downloaded. For details on working with code examples, please read the [Code snippets](https://angular.io/guide/docs-style-guide#code-snippets), [Source code markup](https://angular.io/guide/docs-style-guide#source-code-markup), and [Live examples](https://angular.io/guide/docs-style-guide#live-examples) pages of the [Authors Style Guide](https://angular.io/guide/docs-style-guide).
|
||||
Usamos la herramienta [dgeni](https://github.com/angular/dgeni) para convertir estos archivos en docs que se pueden ver en el doc-viewer.
|
||||
Las [guías de estilo para Autores](https://docs.angular.lat/guide/docs-style-guide) prescriben pautas para
|
||||
escribir páginas de guía, explica cómo usar la documentación de clases y componentes, y cómo marcar el código fuente para producir fragmentos de código.
|
||||
|
||||
We use the [dgeni](https://github.com/angular/dgeni) tool to convert these files into docs that can be viewed in the doc-viewer.
|
||||
### Generando documentos completos
|
||||
|
||||
The [Authors Style Guide](https://angular.io/guide/docs-style-guide) prescribes guidelines for
|
||||
writing guide pages, explains how to use the documentation classes and components, and how to markup sample source code to produce code snippets.
|
||||
La principal tarea para generar los documentos es `yarn docs`. Esto procesará todos los archivos fuente (API y otros), extrayendo la documentación y generando archivos JSON que pueden ser consumidos por el doc-viewer.
|
||||
|
||||
### Generating the complete docs
|
||||
### Generación parcial de doc para editores
|
||||
|
||||
The main task for generating the docs is `yarn docs`. This will process all the source files (API and other),
|
||||
extracting the documentation and generating JSON files that can be consumed by the doc-viewer.
|
||||
La generación completa de documentos puede llevar hasta un minuto. Eso es demasiado lento para la creación y edición eficiente de documentos.
|
||||
|
||||
### Partial doc generation for editors
|
||||
Puedes ealizar pequeños cambios en un editor inteligente que muestre un markdown con formato:
|
||||
>En VS Code, _Cmd-K, V_ abre la vista previa de markdown en el panel lateral; _Cmd-B_ alterna la barra izquierda
|
||||
|
||||
Full doc generation can take up to one minute. That's too slow for efficient document creation and editing.
|
||||
Puedes también mirar los cambios que se muestran correctamente en el doc-viewer
|
||||
con un tiempo de ciclo rápido de edición / visualización.
|
||||
|
||||
You can make small changes in a smart editor that displays formatted markdown:
|
||||
>In VS Code, _Cmd-K, V_ opens markdown preview in side pane; _Cmd-B_ toggles left sidebar
|
||||
Para este propósito, usa la tarea `yarn docs-watch`, que observa los cambios en los archivos de origen y solo vuelve a procesar los archivos necesarios para generar los documentos relacionados con el archivo que ha cambiado.
|
||||
Dado que esta tarea tiene accesos directos, es mucho más rápido (a menudo menos de 1 segundo) pero no producirá contenido de fidelidad completa. Por ejemplo, los enlaces a otros documentoss y ejemplos de código pueden no mostrarse correctamente. Esto se nota especialmente en los enlaces a otros documentos y en los ejemplos incrustados, que no siempre se representan correctamente.
|
||||
|
||||
You also want to see those changes displayed properly in the doc viewer
|
||||
with a quick, edit/view cycle time.
|
||||
La configuración general es la siguiente:
|
||||
|
||||
For this purpose, use the `yarn docs-watch` task, which watches for changes to source files and only
|
||||
re-processes the files necessary to generate the docs that are related to the file that has changed.
|
||||
Since this task takes shortcuts, it is much faster (often less than 1 second) but it won't produce full
|
||||
fidelity content. For example, links to other docs and code examples may not render correctly. This is
|
||||
most particularly noticed in links to other docs and in the embedded examples, which may not always render
|
||||
correctly.
|
||||
|
||||
The general setup is as follows:
|
||||
|
||||
* Open a terminal, ensure the dependencies are installed; run an initial doc generation; then start the doc-viewer:
|
||||
* Abrir una terminal, estar seguro que las dependencias están instaladas; ejecutar una generación inicial del doc; luego iniciar el doc-viewer:
|
||||
|
||||
```bash
|
||||
yarn setup
|
||||
yarn start
|
||||
```
|
||||
|
||||
* Open a second terminal and start watching the docs
|
||||
* Abrir una segunda terminal e iniciar el observador de documentos.
|
||||
|
||||
```bash
|
||||
yarn docs-watch
|
||||
```
|
||||
|
||||
>Alternatively, try the consolidated `serve-and-sync` command that builds, watches and serves in the same terminal window
|
||||
>Alternativamente, prueba el comando fusionado `serve-and-sync` que crea, observa y ejecuta en la misma ventana de la terminal
|
||||
```bash
|
||||
yarn serve-and-sync
|
||||
```
|
||||
|
||||
* Open a browser at https://localhost:4200/ and navigate to the document on which you want to work.
|
||||
You can automatically open the browser by using `yarn start -o` in the first terminal.
|
||||
* Abre un navegador con la siguiente dirección https://localhost:4200/ y navega hasta el documento en el que quieras trabajar.
|
||||
Puedes automáticamente abrir el navegador utilizando `yarn start -o` en la primera terminal.
|
||||
|
||||
* Make changes to the page's associated doc or example files. Every time a file is saved, the doc will
|
||||
be regenerated, the app will rebuild and the page will reload.
|
||||
* Realiza cambios en la página de documentación asociada o en los archivos de ejemplo. Cada vez que un archivo es guardado, la documentación se regenerará, la aplicación se reconstruirá y la página se volverá a cargar.
|
||||
|
||||
* If you get a build error complaining about examples or any other odd behavior, be sure to consult
|
||||
the [Authors Style Guide](https://angular.io/guide/docs-style-guide).
|
||||
*Si recibes un error de compilación acerca de los ejemplos o cualquier otro error, asegúrate de consultar las
|
||||
[guías de estilo para Autores](https://angular.io/guide/docs-style-guide) para más información.
|
||||
|
@ -341,7 +341,7 @@ The following are some of the key AngularJS built-in directives and their equiva
|
||||
In Angular, the template no longer specifies its associated controller.
|
||||
Rather, the component specifies its associated template as part of the component class decorator.
|
||||
|
||||
For more information, see [Architecture Overview](guide/architecture#components).
|
||||
For more information, see [Architecture Overview](guide/architecture#componentes).
|
||||
|
||||
</td>
|
||||
|
||||
@ -1035,7 +1035,7 @@ The Angular code is shown using TypeScript.
|
||||
This is a nonissue in Angular because ES 2015 modules
|
||||
handle the namespacing for you.
|
||||
|
||||
For more information on modules, see the [Modules](guide/architecture#modules) section of the
|
||||
For more information on modules, see the [Modules](guide/architecture#módulos) section of the
|
||||
[Architecture Overview](guide/architecture).
|
||||
</td>
|
||||
|
||||
@ -1112,7 +1112,7 @@ The Angular code is shown using TypeScript.
|
||||
|
||||
This is how you associate a template with logic, which is defined in the component class.
|
||||
|
||||
For more information, see the [Components](guide/architecture#components)
|
||||
For more information, see the [Components](guide/architecture#componentes)
|
||||
section of the [Architecture Overview](guide/architecture) page.
|
||||
</td>
|
||||
|
||||
@ -1144,7 +1144,7 @@ The Angular code is shown using TypeScript.
|
||||
|
||||
In Angular, you create a component class to contain the data model and control methods. Use the TypeScript <code>export</code> keyword to export the class so that the functionality can be imported into NgModules.
|
||||
|
||||
For more information, see the [Components](guide/architecture#components)
|
||||
For more information, see the [Components](guide/architecture#componentes)
|
||||
section of the [Architecture Overview](guide/architecture) page.
|
||||
</td>
|
||||
|
||||
|
665
aio/content/guide/aot-compile.en.md
Normal file
665
aio/content/guide/aot-compile.en.md
Normal file
@ -0,0 +1,665 @@
|
||||
# Ahead-of-time (AOT) compilation
|
||||
|
||||
An Angular application consists mainly of components and their HTML templates. Because the components and templates provided by Angular cannot be understood by the browser directly, Angular applications require a compilation process before they can run in a browser.
|
||||
|
||||
The Angular [ahead-of-time (AOT) compiler](guide/glossary#aot) converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase _before_ the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the browser.
|
||||
|
||||
This guide explains how to specify metadata and apply available compiler options to compile your applications efficiently using the AOT compiler.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=anphffaCZrQ">Watch Alex Rickabaugh explain the Angular compiler</a> at AngularConnect 2019.
|
||||
|
||||
</div>
|
||||
|
||||
{@a why-aot}
|
||||
|
||||
Here are some reasons you might want to use AOT.
|
||||
|
||||
* *Faster rendering*
|
||||
With AOT, the browser downloads a pre-compiled version of the application.
|
||||
The browser loads executable code so it can render the application immediately, without waiting to compile the app first.
|
||||
|
||||
* *Fewer asynchronous requests*
|
||||
The compiler _inlines_ external HTML templates and CSS style sheets within the application JavaScript,
|
||||
eliminating separate ajax requests for those source files.
|
||||
|
||||
* *Smaller Angular framework download size*
|
||||
There's no need to download the Angular compiler if the app is already compiled.
|
||||
The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.
|
||||
|
||||
* *Detect template errors earlier*
|
||||
The AOT compiler detects and reports template binding errors during the build step
|
||||
before users can see them.
|
||||
|
||||
* *Better security*
|
||||
AOT compiles HTML templates and components into JavaScript files long before they are served to the client.
|
||||
With no templates to read and no risky client-side HTML or JavaScript evaluation,
|
||||
there are fewer opportunities for injection attacks.
|
||||
|
||||
{@a overview}
|
||||
|
||||
## Choosing a compiler
|
||||
|
||||
Angular offers two ways to compile your application:
|
||||
|
||||
* **_Just-in-Time_ (JIT)**, which compiles your app in the browser at runtime. This was the default until Angular 8.
|
||||
* **_Ahead-of-Time_ (AOT)**, which compiles your app and libraries at build time. This is the default since Angular 9.
|
||||
|
||||
When you run the [`ng build`](cli/build) (build only) or [`ng serve`](cli/serve) (build and serve locally) CLI commands, the type of compilation (JIT or AOT) depends on the value of the `aot` property in your build configuration specified in `angular.json`. By default, `aot` is set to `true` for new CLI apps.
|
||||
|
||||
See the [CLI command reference](cli) and [Building and serving Angular apps](guide/build) for more information.
|
||||
|
||||
## How AOT works
|
||||
|
||||
The Angular AOT compiler extracts **metadata** to interpret the parts of the application that Angular is supposed to manage.
|
||||
You can specify the metadata explicitly in **decorators** such as `@Component()` and `@Input()`, or implicitly in the constructor declarations of the decorated classes.
|
||||
The metadata tells Angular how to construct instances of your application classes and interact with them at runtime.
|
||||
|
||||
In the following example, the `@Component()` metadata object and the class constructor tell Angular how to create and display an instance of `TypicalComponent`.
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'app-typical',
|
||||
template: '<div>A typical component for {{data.name}}</div>'
|
||||
)}
|
||||
export class TypicalComponent {
|
||||
@Input() data: TypicalData;
|
||||
constructor(private someService: SomeService) { ... }
|
||||
}
|
||||
```
|
||||
|
||||
The Angular compiler extracts the metadata _once_ and generates a _factory_ for `TypicalComponent`.
|
||||
When it needs to create a `TypicalComponent` instance, Angular calls the factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency.
|
||||
|
||||
### Compilation phases
|
||||
|
||||
There are three phases of AOT compilation.
|
||||
* Phase 1 is *code analysis*.
|
||||
In this phase, the TypeScript compiler and *AOT collector* create a representation of the source. The collector does not attempt to interpret the metadata it collects. It represents the metadata as best it can and records errors when it detects a metadata syntax violation.
|
||||
|
||||
* Phase 2 is *code generation*.
|
||||
In this phase, the compiler's `StaticReflector` interprets the metadata collected in phase 1, performs additional validation of the metadata, and throws an error if it detects a metadata restriction violation.
|
||||
|
||||
* Phase 3 is *template type checking*.
|
||||
In this optional phase, the Angular *template compiler* uses the TypeScript compiler to validate the binding expressions in templates. You can enable this phase explicitly by setting the `fullTemplateTypeCheck` configuration option; see [Angular compiler options](guide/angular-compiler-options).
|
||||
|
||||
|
||||
### Metadata restrictions
|
||||
|
||||
You write metadata in a _subset_ of TypeScript that must conform to the following general constraints:
|
||||
|
||||
* Limit [expression syntax](#expression-syntax) to the supported subset of JavaScript.
|
||||
* Only reference exported symbols after [code folding](#code-folding).
|
||||
* Only call [functions supported](#supported-functions) by the compiler.
|
||||
* Decorated and data-bound class members must be public.
|
||||
|
||||
For additional guidelines and instructions on preparing an application for AOT compilation, see [Angular: Writing AOT-friendly applications](https://medium.com/sparkles-blog/angular-writing-aot-friendly-applications-7b64c8afbe3f).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Errors in AOT compilation commonly occur because of metadata that does not conform to the compiler's requirements (as described more fully below).
|
||||
For help in understanding and resolving these problems, see [AOT Metadata Errors](guide/aot-metadata-errors).
|
||||
|
||||
</div>
|
||||
|
||||
### Configuring AOT compilation
|
||||
|
||||
You can provide options in the [TypeScript configuration file](guide/typescript-configuration) that controls the compilation process. See [Angular compiler options](guide/angular-compiler-options) for a complete list of available options.
|
||||
|
||||
## Phase 1: Code analysis
|
||||
|
||||
The TypeScript compiler does some of the analytic work of the first phase. It emits the `.d.ts` _type definition files_ with type information that the AOT compiler needs to generate application code.
|
||||
At the same time, the AOT **collector** analyzes the metadata recorded in the Angular decorators and outputs metadata information in **`.metadata.json`** files, one per `.d.ts` file.
|
||||
|
||||
You can think of `.metadata.json` as a diagram of the overall structure of a decorator's metadata, represented as an [abstract syntax tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Angular's [schema.ts](https://github.com/angular/angular/blob/master/packages/compiler-cli/src/metadata/schema.ts)
|
||||
describes the JSON format as a collection of TypeScript interfaces.
|
||||
|
||||
</div>
|
||||
|
||||
{@a expression-syntax}
|
||||
### Expression syntax limitations
|
||||
|
||||
The AOT collector only understands a subset of JavaScript.
|
||||
Define metadata objects with the following limited syntax:
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
</style>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Syntax</th>
|
||||
<th>Example</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal object </td>
|
||||
<td><code>{cherry: true, apple: true, mincemeat: false}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal array </td>
|
||||
<td><code>['cherries', 'flour', 'sugar']</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Spread in literal array</td>
|
||||
<td><code>['apples', 'flour', ...the_rest]</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Calls</td>
|
||||
<td><code>bake(ingredients)</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>New</td>
|
||||
<td><code>new Oven()</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Property access</td>
|
||||
<td><code>pie.slice</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Array index</td>
|
||||
<td><code>ingredients[0]</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Identity reference</td>
|
||||
<td><code>Component</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>A template string</td>
|
||||
<td><code>`pie is ${multiplier} times better than cake`</code></td>
|
||||
<tr>
|
||||
<td>Literal string</td>
|
||||
<td><code>pi</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal number</td>
|
||||
<td><code>3.14153265</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal boolean</td>
|
||||
<td><code>true</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal null</td>
|
||||
<td><code>null</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported prefix operator </td>
|
||||
<td><code>!cake</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported binary operator </td>
|
||||
<td><code>a+b</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Conditional operator</td>
|
||||
<td><code>a ? b : c</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Parentheses</td>
|
||||
<td><code>(a+b)</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
If an expression uses unsupported syntax, the collector writes an error node to the `.metadata.json` file.
|
||||
The compiler later reports the error if it needs that piece of metadata to generate the application code.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
If you want `ngc` to report syntax errors immediately rather than produce a `.metadata.json` file with errors, set the `strictMetadataEmit` option in the TypeScript configuration file.
|
||||
|
||||
```
|
||||
"angularCompilerOptions": {
|
||||
...
|
||||
"strictMetadataEmit" : true
|
||||
}
|
||||
```
|
||||
|
||||
Angular libraries have this option to ensure that all Angular `.metadata.json` files are clean and it is a best practice to do the same when building your own libraries.
|
||||
|
||||
</div>
|
||||
|
||||
{@a function-expression}
|
||||
{@a arrow-functions}
|
||||
### No arrow functions
|
||||
|
||||
The AOT compiler does not support [function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)
|
||||
and [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), also called _lambda_ functions.
|
||||
|
||||
Consider the following component decorator:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
...
|
||||
providers: [{provide: server, useFactory: () => new Server()}]
|
||||
})
|
||||
```
|
||||
|
||||
The AOT collector does not support the arrow function, `() => new Server()`, in a metadata expression.
|
||||
It generates an error node in place of the function.
|
||||
When the compiler later interprets this node, it reports an error that invites you to turn the arrow function into an _exported function_.
|
||||
|
||||
You can fix the error by converting to this:
|
||||
|
||||
```typescript
|
||||
export function serverFactory() {
|
||||
return new Server();
|
||||
}
|
||||
|
||||
@Component({
|
||||
...
|
||||
providers: [{provide: server, useFactory: serverFactory}]
|
||||
})
|
||||
```
|
||||
|
||||
In version 5 and later, the compiler automatically performs this rewriting while emitting the `.js` file.
|
||||
|
||||
{@a exported-symbols}
|
||||
{@a code-folding}
|
||||
### Code folding
|
||||
|
||||
The compiler can only resolve references to **_exported_** symbols.
|
||||
The collector, however, can evaluate an expression during collection and record the result in the `.metadata.json`, rather than the original expression.
|
||||
This allows you to make limited use of non-exported symbols within expressions.
|
||||
|
||||
For example, the collector can evaluate the expression `1 + 2 + 3 + 4` and replace it with the result, `10`.
|
||||
This process is called _folding_. An expression that can be reduced in this manner is _foldable_.
|
||||
|
||||
{@a var-declaration}
|
||||
The collector can evaluate references to module-local `const` declarations and initialized `var` and `let` declarations, effectively removing them from the `.metadata.json` file.
|
||||
|
||||
Consider the following component definition:
|
||||
|
||||
```typescript
|
||||
const template = '<div>{{hero.name}}</div>';
|
||||
|
||||
@Component({
|
||||
selector: 'app-hero',
|
||||
template: template
|
||||
})
|
||||
export class HeroComponent {
|
||||
@Input() hero: Hero;
|
||||
}
|
||||
```
|
||||
|
||||
The compiler could not refer to the `template` constant because it isn't exported.
|
||||
The collector, however, can fold the `template` constant into the metadata definition by in-lining its contents.
|
||||
The effect is the same as if you had written:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'app-hero',
|
||||
template: '<div>{{hero.name}}</div>'
|
||||
})
|
||||
export class HeroComponent {
|
||||
@Input() hero: Hero;
|
||||
}
|
||||
```
|
||||
|
||||
There is no longer a reference to `template` and, therefore, nothing to trouble the compiler when it later interprets the _collector's_ output in `.metadata.json`.
|
||||
|
||||
You can take this example a step further by including the `template` constant in another expression:
|
||||
|
||||
```typescript
|
||||
const template = '<div>{{hero.name}}</div>';
|
||||
|
||||
@Component({
|
||||
selector: 'app-hero',
|
||||
template: template + '<div>{{hero.title}}</div>'
|
||||
})
|
||||
export class HeroComponent {
|
||||
@Input() hero: Hero;
|
||||
}
|
||||
```
|
||||
|
||||
The collector reduces this expression to its equivalent _folded_ string:
|
||||
|
||||
```
|
||||
'<div>{{hero.name}}</div><div>{{hero.title}}</div>'
|
||||
```
|
||||
|
||||
#### Foldable syntax
|
||||
|
||||
The following table describes which expressions the collector can and cannot fold:
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
</style>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Syntax</th>
|
||||
<th>Foldable</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal object </td>
|
||||
<td>yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal array </td>
|
||||
<td>yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Spread in literal array</td>
|
||||
<td>no</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Calls</td>
|
||||
<td>no</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>New</td>
|
||||
<td>no</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Property access</td>
|
||||
<td>yes, if target is foldable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Array index</td>
|
||||
<td> yes, if target and index are foldable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Identity reference</td>
|
||||
<td>yes, if it is a reference to a local</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>A template with no substitutions</td>
|
||||
<td>yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>A template with substitutions</td>
|
||||
<td>yes, if the substitutions are foldable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal string</td>
|
||||
<td>yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal number</td>
|
||||
<td>yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal boolean</td>
|
||||
<td>yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal null</td>
|
||||
<td>yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported prefix operator </td>
|
||||
<td>yes, if operand is foldable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported binary operator </td>
|
||||
<td>yes, if both left and right are foldable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Conditional operator</td>
|
||||
<td>yes, if condition is foldable </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Parentheses</td>
|
||||
<td>yes, if the expression is foldable</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
If an expression is not foldable, the collector writes it to `.metadata.json` as an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) for the compiler to resolve.
|
||||
|
||||
|
||||
## Phase 2: code generation
|
||||
|
||||
The collector makes no attempt to understand the metadata that it collects and outputs to `.metadata.json`.
|
||||
It represents the metadata as best it can and records errors when it detects a metadata syntax violation.
|
||||
It's the compiler's job to interpret the `.metadata.json` in the code generation phase.
|
||||
|
||||
The compiler understands all syntax forms that the collector supports, but it may reject _syntactically_ correct metadata if the _semantics_ violate compiler rules.
|
||||
|
||||
### Public symbols
|
||||
|
||||
The compiler can only reference _exported symbols_.
|
||||
|
||||
* Decorated component class members must be public. You cannot make an `@Input()` property private or protected.
|
||||
* Data bound properties must also be public.
|
||||
|
||||
```typescript
|
||||
// BAD CODE - title is private
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
template: '<h1>{{title}}</h1>'
|
||||
})
|
||||
export class AppComponent {
|
||||
private title = 'My App'; // Bad
|
||||
}
|
||||
```
|
||||
|
||||
{@a supported-functions}
|
||||
|
||||
### Supported classes and functions
|
||||
|
||||
The collector can represent a function call or object creation with `new` as long as the syntax is valid.
|
||||
The compiler, however, can later refuse to generate a call to a _particular_ function or creation of a _particular_ object.
|
||||
|
||||
The compiler can only create instances of certain classes, supports only core decorators, and only supports calls to macros (functions or static methods) that return expressions.
|
||||
* New instances
|
||||
|
||||
The compiler only allows metadata that create instances of the class `InjectionToken` from `@angular/core`.
|
||||
|
||||
* Supported decorators
|
||||
|
||||
The compiler only supports metadata for the [Angular decorators in the `@angular/core` module](api/core#decorators).
|
||||
|
||||
* Function calls
|
||||
|
||||
Factory functions must be exported, named functions.
|
||||
The AOT compiler does not support lambda expressions ("arrow functions") for factory functions.
|
||||
|
||||
{@a function-calls}
|
||||
### Functions and static method calls
|
||||
|
||||
The collector accepts any function or static method that contains a single `return` statement.
|
||||
The compiler, however, only supports macros in the form of functions or static methods that return an *expression*.
|
||||
|
||||
For example, consider the following function:
|
||||
|
||||
```typescript
|
||||
export function wrapInArray<T>(value: T): T[] {
|
||||
return [value];
|
||||
}
|
||||
```
|
||||
|
||||
You can call the `wrapInArray` in a metadata definition because it returns the value of an expression that conforms to the compiler's restrictive JavaScript subset.
|
||||
|
||||
You might use `wrapInArray()` like this:
|
||||
|
||||
```typescript
|
||||
@NgModule({
|
||||
declarations: wrapInArray(TypicalComponent)
|
||||
})
|
||||
export class TypicalModule {}
|
||||
```
|
||||
|
||||
The compiler treats this usage as if you had written:
|
||||
|
||||
```typescript
|
||||
@NgModule({
|
||||
declarations: [TypicalComponent]
|
||||
})
|
||||
export class TypicalModule {}
|
||||
```
|
||||
The Angular [`RouterModule`](api/router/RouterModule) exports two macro static methods, `forRoot` and `forChild`, to help declare root and child routes.
|
||||
Review the [source code](https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts#L139 "RouterModule.forRoot source code")
|
||||
for these methods to see how macros can simplify configuration of complex [NgModules](guide/ngmodules).
|
||||
|
||||
{@a metadata-rewriting}
|
||||
|
||||
### Metadata rewriting
|
||||
|
||||
The compiler treats object literals containing the fields `useClass`, `useValue`, `useFactory`, and `data` specially, converting the expression initializing one of these fields into an exported variable that replaces the expression.
|
||||
This process of rewriting these expressions removes all the restrictions on what can be in them because
|
||||
the compiler doesn't need to know the expression's value—it just needs to be able to generate a reference to the value.
|
||||
|
||||
You might write something like:
|
||||
|
||||
```typescript
|
||||
class TypicalServer {
|
||||
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
providers: [{provide: SERVER, useFactory: () => TypicalServer}]
|
||||
})
|
||||
export class TypicalModule {}
|
||||
```
|
||||
|
||||
Without rewriting, this would be invalid because lambdas are not supported and `TypicalServer` is not exported.
|
||||
To allow this, the compiler automatically rewrites this to something like:
|
||||
|
||||
```typescript
|
||||
class TypicalServer {
|
||||
|
||||
}
|
||||
|
||||
export const ɵ0 = () => new TypicalServer();
|
||||
|
||||
@NgModule({
|
||||
providers: [{provide: SERVER, useFactory: ɵ0}]
|
||||
})
|
||||
export class TypicalModule {}
|
||||
```
|
||||
|
||||
This allows the compiler to generate a reference to `ɵ0` in the factory without having to know what the value of `ɵ0` contains.
|
||||
|
||||
The compiler does the rewriting during the emit of the `.js` file.
|
||||
It does not, however, rewrite the `.d.ts` file, so TypeScript doesn't recognize it as being an export. and it does not interfere with the ES module's exported API.
|
||||
|
||||
|
||||
{@a binding-expression-validation}
|
||||
|
||||
## Phase 3: Template type checking
|
||||
|
||||
One of the Angular compiler's most helpful features is the ability to type-check expressions within templates, and catch any errors before they cause crashes at runtime.
|
||||
In the template type-checking phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates.
|
||||
|
||||
Enable this phase explicitly by adding the compiler option `"fullTemplateTypeCheck"` in the `"angularCompilerOptions"` of the project's TypeScript configuration file
|
||||
(see [Angular Compiler Options](guide/angular-compiler-options)).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
In [Angular Ivy](guide/ivy), the template type checker has been completely rewritten to be more capable as well as stricter, meaning it can catch a variety of new errors that the previous type checker would not detect.
|
||||
|
||||
As a result, templates that previously compiled under View Engine can fail type checking under Ivy. This can happen because Ivy's stricter checking catches genuine errors, or because application code is not typed correctly, or because the application uses libraries in which typings are inaccurate or not specific enough.
|
||||
|
||||
This stricter type checking is not enabled by default in version 9, but can be enabled by setting the `strictTemplates` configuration option.
|
||||
We do expect to make strict type checking the default in the future.
|
||||
|
||||
For more information about type-checking options, and about improvements to template type checking in version 9 and above, see [Template type checking](guide/template-typecheck).
|
||||
|
||||
</div>
|
||||
|
||||
Template validation produces error messages when a type error is detected in a template binding
|
||||
expression, similar to how type errors are reported by the TypeScript compiler against code in a `.ts`
|
||||
file.
|
||||
|
||||
For example, consider the following component:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '{{person.addresss.street}}'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
}
|
||||
```
|
||||
|
||||
This produces the following error:
|
||||
|
||||
```
|
||||
my.component.ts.MyComponent.html(1,1): : Property 'addresss' does not exist on type 'Person'. Did you mean 'address'?
|
||||
```
|
||||
|
||||
The file name reported in the error message, `my.component.ts.MyComponent.html`, is a synthetic file
|
||||
generated by the template compiler that holds contents of the `MyComponent` class template.
|
||||
The compiler never writes this file to disk.
|
||||
The line and column numbers are relative to the template string in the `@Component` annotation of the class, `MyComponent` in this case.
|
||||
If a component uses `templateUrl` instead of `template`, the errors are reported in the HTML file referenced by the `templateUrl` instead of a synthetic file.
|
||||
|
||||
The error location is the beginning of the text node that contains the interpolation expression with the error.
|
||||
If the error is in an attribute binding such as `[value]="person.address.street"`, the error
|
||||
location is the location of the attribute that contains the error.
|
||||
|
||||
The validation uses the TypeScript type checker and the options supplied to the TypeScript compiler to control how detailed the type validation is.
|
||||
For example, if the `strictTypeChecks` is specified, the error
|
||||
```my.component.ts.MyComponent.html(1,1): : Object is possibly 'undefined'```
|
||||
is reported as well as the above error message.
|
||||
|
||||
### Type narrowing
|
||||
|
||||
The expression used in an `ngIf` directive is used to narrow type unions in the Angular
|
||||
template compiler, the same way the `if` expression does in TypeScript.
|
||||
For example, to avoid `Object is possibly 'undefined'` error in the template above, modify it to only emit the interpolation if the value of `person` is initialized as shown below:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person"> {{person.addresss.street}} </span>'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
}
|
||||
```
|
||||
|
||||
Using `*ngIf` allows the TypeScript compiler to infer that the `person` used in the binding expression will never be `undefined`.
|
||||
|
||||
For more information about input type narrowing, see [Input setter coercion](guide/template-typecheck#input-setter-coercion) and [Improving template type checking for custom directives](guide/structural-directives#directive-type-checks).
|
||||
|
||||
### Non-null type assertion operator
|
||||
|
||||
Use the [non-null type assertion operator](guide/template-expression-operators#non-null-assertion-operator) to suppress the `Object is possibly 'undefined'` error when it is inconvenient to use `*ngIf` or when some constraint in the component ensures that the expression is always non-null when the binding expression is interpolated.
|
||||
|
||||
In the following example, the `person` and `address` properties are always set together, implying that `address` is always non-null if `person` is non-null.
|
||||
There is no convenient way to describe this constraint to TypeScript and the template compiler, but the error is suppressed in the example by using `address!.street`.
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person"> {{person.name}} lives on {{address!.street}} </span>'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
address?: Address;
|
||||
|
||||
setData(person: Person, address: Address) {
|
||||
this.person = person;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The non-null assertion operator should be used sparingly as refactoring of the component might break this constraint.
|
||||
|
||||
In this example it is recommended to include the checking of `address` in the `*ngIf` as shown below:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person && address"> {{person.name}} lives on {{address.street}} </span>'
|
||||
})
|
||||
class MyComponent {
|
||||
person?: Person;
|
||||
address?: Address;
|
||||
|
||||
setData(person: Person, address: Address) {
|
||||
this.person = person;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
```
|
@ -1,62 +1,59 @@
|
||||
# Ahead-of-time (AOT) compilation
|
||||
# Compilación anticipada (AOT)
|
||||
|
||||
An Angular application consists mainly of components and their HTML templates. Because the components and templates provided by Angular cannot be understood by the browser directly, Angular applications require a compilation process before they can run in a browser.
|
||||
Una aplicación Angular consta principalmente de componentes y sus plantillas HTML. Los componentes y plantillas proporcionados por Angular no pueden ser entendidos por el navegador directamente, las aplicaciones en Angular requieren un proceso de compilación antes de que puedan correr en un navegador.
|
||||
|
||||
The Angular [ahead-of-time (AOT) compiler](guide/glossary#aot) converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase _before_ the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the browser.
|
||||
La [compilación anticipada de Angular (AOT)](guide/glossary#aot) convierte plantillas y código de TypeScript en eficiente código JavaScript durante la fase de construcción _antes_ de que el navegador descargue y corra el código. Compilando tu aplicación durante el proceso de construcción se proporciona una renderización más rápida en el navegador.
|
||||
|
||||
This guide explains how to specify metadata and apply available compiler options to compile your applications efficiently using the AOT compiler.
|
||||
Esta guía explica como especificar metadatos y aplicar las opciones del compilador disponibles para compilar aplicaciones eficientemente usando la compilación anticipada (AOT).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=anphffaCZrQ">Watch Alex Rickabaugh explain the Angular compiler</a> at AngularConnect 2019.
|
||||
<a href="https://www.youtube.com/watch?v=anphffaCZrQ">Mira a Alex Rickabaugh explicando el compilador de Angular en AngularConnect 2019.
|
||||
|
||||
</div>
|
||||
|
||||
{@a why-aot}
|
||||
|
||||
Here are some reasons you might want to use AOT.
|
||||
Aquí algunas razones por las qué podrías querer usar AOT.
|
||||
|
||||
* *Faster rendering*
|
||||
With AOT, the browser downloads a pre-compiled version of the application.
|
||||
The browser loads executable code so it can render the application immediately, without waiting to compile the app first.
|
||||
* *Renderizado más rápido*
|
||||
Con AOT, el navegador descarga una versión pre compilada de una aplicación.
|
||||
El navegador carga el código ejecutable para que pueda renderizar la aplicación inmediatamente, sin esperar a compilar la aplicación primero.
|
||||
|
||||
* *Fewer asynchronous requests*
|
||||
The compiler _inlines_ external HTML templates and CSS style sheets within the application JavaScript,
|
||||
eliminating separate ajax requests for those source files.
|
||||
* *Menos solicitudes asincrónicas*
|
||||
El compilador _inserta_ plantillas HTML y hojas de estilo CSS externas dentro de la aplicación JavaScript, eliminando solicitudes ajax separadas para esos archivos fuente.
|
||||
|
||||
* *Smaller Angular framework download size*
|
||||
There's no need to download the Angular compiler if the app is already compiled.
|
||||
The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.
|
||||
* *Angular pesa menos*
|
||||
No existe necesidad de incluir el compilador de Angular si la aplicación ya esta compilada.
|
||||
El compilador es aproximadamente la mitad de Angular en si mismo, así que omitíendolo se reduce drásticamente el peso de la aplicación.
|
||||
|
||||
* *Detect template errors earlier*
|
||||
The AOT compiler detects and reports template binding errors during the build step
|
||||
before users can see them.
|
||||
* *Detecte errores en platillas antes*
|
||||
El compilador AOT detecta y reporta errores de enlace de datos en plantillas durante el paso de construcción antes que los usuarios puedan verlos.
|
||||
|
||||
* *Better security*
|
||||
AOT compiles HTML templates and components into JavaScript files long before they are served to the client.
|
||||
With no templates to read and no risky client-side HTML or JavaScript evaluation,
|
||||
there are fewer opportunities for injection attacks.
|
||||
* *Mejor seguridad*
|
||||
AOT compila las plantillas HTML y componentes en archivos JavaScript mucho antes de que se sirvan a el cliente.
|
||||
Sin plantillas para leer y sin evaluaciones de JavaScript o HTML del lado del cliente riesgosas, existen pocas oportunidades para ataques de inyección.
|
||||
|
||||
{@a overview}
|
||||
|
||||
## Choosing a compiler
|
||||
## Eligiendo un compilador.
|
||||
|
||||
Angular offers two ways to compile your application:
|
||||
Angular ofrece dos formas para compilar tu aplicación:
|
||||
|
||||
* **_Just-in-Time_ (JIT)**, which compiles your app in the browser at runtime. This was the default until Angular 8.
|
||||
* **_Ahead-of-Time_ (AOT)**, which compiles your app and libraries at build time. This is the default since Angular 9.
|
||||
* **_Just-in-Time_ (JIT)**, cuando compila tu aplicación en el navegador en tiempo de ejecución. Este fué el modo de compilación por defecto hasta Angular 8.
|
||||
* **_Ahead-of-Time_ (AOT)**, cuando compila tu aplicación y librerías en el tiempo de construcción. Este es el modo de compilación por defecto desde Angular 9.
|
||||
|
||||
When you run the [`ng build`](cli/build) (build only) or [`ng serve`](cli/serve) (build and serve locally) CLI commands, the type of compilation (JIT or AOT) depends on the value of the `aot` property in your build configuration specified in `angular.json`. By default, `aot` is set to `true` for new CLI apps.
|
||||
Cuando ejecutas los comandos del CLI [`ng build`](cli/build) (solo construcción) o [`ng serve`](cli/serve) (construye y sirve localmente), el tipo de compilación (JIT o AOT) depende del valor de la propiedad `aot` en tu configuración de construcción especificada en el archivo `angular.json`. Por defecto, `aot` esta establecido en `true` para nuevas aplicaciones.
|
||||
|
||||
See the [CLI command reference](cli) and [Building and serving Angular apps](guide/build) for more information.
|
||||
Mira la [referencia de comandos del CLI](cli) y [Construyendo y sirviendo Angular apps](guide/build) para más información.
|
||||
|
||||
## How AOT works
|
||||
## Como funciona AOT
|
||||
|
||||
The Angular AOT compiler extracts **metadata** to interpret the parts of the application that Angular is supposed to manage.
|
||||
You can specify the metadata explicitly in **decorators** such as `@Component()` and `@Input()`, or implicitly in the constructor declarations of the decorated classes.
|
||||
The metadata tells Angular how to construct instances of your application classes and interact with them at runtime.
|
||||
El compilador de Angular AOT extrae **metadatos** para interpretar las partes de la aplicación que se supone que Angular maneja.
|
||||
Puedes especificar los metadatos explícitamente en **decoradores** como `@Component()` y `@Input()`, o implícitamente en las declaraciones del constructor de las clases decoradas.
|
||||
Los metadatos le dicen a Angular como construir instancias de clases e interactuar con ellas en tiempo de ejecución.
|
||||
|
||||
In the following example, the `@Component()` metadata object and the class constructor tell Angular how to create and display an instance of `TypicalComponent`.
|
||||
En el siguiente ejemplo, los metadatos de `@Component()` y el constructor le dicen a Angular como crear y mostrar una instancia de `TypicalComponent`.
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
@ -69,63 +66,63 @@ export class TypicalComponent {
|
||||
}
|
||||
```
|
||||
|
||||
The Angular compiler extracts the metadata _once_ and generates a _factory_ for `TypicalComponent`.
|
||||
When it needs to create a `TypicalComponent` instance, Angular calls the factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency.
|
||||
El compilador de Angular extrae los metadatos _una_ vez y genera una _fabrica_ para `TypicalComponent`.
|
||||
Cuando este necesita crear una instancia de `TypicalComponent`, Angular llama a la fabrica, el cuál produce un nuevo elemento visual, vinculado a una nueva instancia la clase del componente con su dependencia inyectada.
|
||||
|
||||
### Compilation phases
|
||||
### Fases de compilación
|
||||
|
||||
There are three phases of AOT compilation.
|
||||
* Phase 1 is *code analysis*.
|
||||
In this phase, the TypeScript compiler and *AOT collector* create a representation of the source. The collector does not attempt to interpret the metadata it collects. It represents the metadata as best it can and records errors when it detects a metadata syntax violation.
|
||||
Existen tres fases de compilación en AOT.
|
||||
|
||||
* Phase 2 is *code generation*.
|
||||
In this phase, the compiler's `StaticReflector` interprets the metadata collected in phase 1, performs additional validation of the metadata, and throws an error if it detects a metadata restriction violation.
|
||||
* Fase 1: *análisis de código*
|
||||
En esta fase, el compilador de TypeScript y el *recolector AOT* crea una representación de la fuente. El recolector no intenta interpretar los metadatos recopilados. Estos representan los metadatos lo mejor que pueden y registra errores cuando este detecta un violación de sintaxis en los metadatos.
|
||||
|
||||
* Phase 3 is *template type checking*.
|
||||
In this optional phase, the Angular *template compiler* uses the TypeScript compiler to validate the binding expressions in templates. You can enable this phase explicitly by setting the `fullTemplateTypeCheck` configuration option; see [Angular compiler options](guide/angular-compiler-options).
|
||||
* Fase 2: *generación de código*
|
||||
En esta fase, el `StaticReflector` del compilador interpreta los metadatos recolectados en la fase 1, realiza validaciones adicionales de los metadatos y lanza un error si este detecta una violación de la restricción de metadatos.
|
||||
|
||||
* Fase 3: *verificación de tipos en plantillas*
|
||||
Esta fase es opcional, el *compilador de plantillas* de Angular usa el compilador de Typescript para validar las expresiones de enlaces de datos en las plantillas. Puedes habilitar esta fase explícitamente configurando la opción `fullTemplateTypeCheck`; revisa [Opciones del Compilador Angular](guide/angular-compiler-options).
|
||||
|
||||
|
||||
### Metadata restrictions
|
||||
### Restricciones de los metadatos
|
||||
|
||||
You write metadata in a _subset_ of TypeScript that must conform to the following general constraints:
|
||||
Escribe metadatos en un _subconjunto_ de TypeScript que debe cumplir las siguientes restricciones generales:
|
||||
|
||||
* Limit [expression syntax](#expression-syntax) to the supported subset of JavaScript.
|
||||
* Only reference exported symbols after [code folding](#code-folding).
|
||||
* Only call [functions supported](#supported-functions) by the compiler.
|
||||
* Decorated and data-bound class members must be public.
|
||||
* Limita la [sintaxis de expresiones](#expression-syntax) al subconjunto soportado de JavaScript.
|
||||
* Solo haz referencia a los símbolos exportados después del [plegado de código](#code-folding).
|
||||
* Solo llame [funciones compátibles](#supported-functions) por el compilador.
|
||||
* Miembros de clase decorados y con enlaces de datos deben ser públicos.
|
||||
|
||||
For additional guidelines and instructions on preparing an application for AOT compilation, see [Angular: Writing AOT-friendly applications](https://medium.com/sparkles-blog/angular-writing-aot-friendly-applications-7b64c8afbe3f).
|
||||
Para guías e instrucciones adicionales al preparar una aplicación para compilación anticipada (AOT), revise [Angular: Writing AOT-friendly applications](https://medium.com/sparkles-blog/angular-writing-aot-friendly-applications-7b64c8afbe3f).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Errors in AOT compilation commonly occur because of metadata that does not conform to the compiler's requirements (as described more fully below).
|
||||
For help in understanding and resolving these problems, see [AOT Metadata Errors](guide/aot-metadata-errors).
|
||||
Los errores en compilación anticipada (AOT) comúnmente ocurren debido a que los metadatos no se ajustan a los requisitos del compilador (como se describen con más detalle a continuación).
|
||||
Para ayudar a entender y resolver estos problemas, revisa [Errores de metadatos en AOT](guide/aot-metadata-errors).
|
||||
|
||||
</div>
|
||||
|
||||
### Configuring AOT compilation
|
||||
### Configurando la compilación anticipada (AOT).
|
||||
|
||||
You can provide options in the [TypeScript configuration file](guide/typescript-configuration) that controls the compilation process. See [Angular compiler options](guide/angular-compiler-options) for a complete list of available options.
|
||||
Puedes proporcionar opciones en el [archivo de configuración de TypeScript](guide/typescript-configuration) que controlan el proceso de compilación. Revisa [las opciones de compilación de Angular](guide/angular-compiler-options) para una lista completa de opciones disponibles.
|
||||
|
||||
## Phase 1: Code analysis
|
||||
## Fase 1: Análisis de código.
|
||||
|
||||
The TypeScript compiler does some of the analytic work of the first phase. It emits the `.d.ts` _type definition files_ with type information that the AOT compiler needs to generate application code.
|
||||
At the same time, the AOT **collector** analyzes the metadata recorded in the Angular decorators and outputs metadata information in **`.metadata.json`** files, one per `.d.ts` file.
|
||||
El compilador de TypeScript realiza parte del trabajo analítico en la primer fase. Este emite los _archivos de definición de tipos_ `.d.ts` con el tipo de información que el compilador AOT necesita para generar el código de la aplicación.
|
||||
Al mismo tiempo, el **recolector** AOT analiza los metadatos registrados en los decoradores de Angular y genera información de metadatos en archivos **`.metadata.json`**, uno por archivo `.d.ts`.
|
||||
|
||||
You can think of `.metadata.json` as a diagram of the overall structure of a decorator's metadata, represented as an [abstract syntax tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree).
|
||||
Puedes pensar en `.metadata.json` como un diagrama de la estructura general de los metadatos de un decorador, representados como un [árbol de sintaxis abstracta (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Angular's [schema.ts](https://github.com/angular/angular/blob/master/packages/compiler-cli/src/metadata/schema.ts)
|
||||
describes the JSON format as a collection of TypeScript interfaces.
|
||||
El [schema.ts](https://github.com/angular/angular/blob/master/packages/compiler-cli/src/metadata/schema.ts) de Angular describe el formato JSON como una colección de interfaces de TypeScript.
|
||||
|
||||
</div>
|
||||
|
||||
{@a expression-syntax}
|
||||
### Expression syntax limitations
|
||||
### Limitaciones del sintaxis de expresión.
|
||||
|
||||
The AOT collector only understands a subset of JavaScript.
|
||||
Define metadata objects with the following limited syntax:
|
||||
El recolector de AOT solo entiende un subconjunto de JavaScript.
|
||||
Defina objetos de metadatos con la siguiente sintaxis limitada:
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
@ -133,85 +130,84 @@ Define metadata objects with the following limited syntax:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Syntax</th>
|
||||
<th>Example</th>
|
||||
<th>Sintaxis</th>
|
||||
<th>Ejemplo</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal object </td>
|
||||
<td>Objeto literal </td>
|
||||
<td><code>{cherry: true, apple: true, mincemeat: false}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal array </td>
|
||||
<td>Colección literal </td>
|
||||
<td><code>['cherries', 'flour', 'sugar']</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Spread in literal array</td>
|
||||
<td>Operador spread en colección literal</td>
|
||||
<td><code>['apples', 'flour', ...the_rest]</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Calls</td>
|
||||
<td>Llamadas</td>
|
||||
<td><code>bake(ingredients)</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>New</td>
|
||||
<td>Nuevo</td>
|
||||
<td><code>new Oven()</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Property access</td>
|
||||
<td>Acceso a propiedades</td>
|
||||
<td><code>pie.slice</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Array index</td>
|
||||
<td>Indices de colección</td>
|
||||
<td><code>ingredients[0]</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Identity reference</td>
|
||||
<td>Referencia de identidad</td>
|
||||
<td><code>Component</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>A template string</td>
|
||||
<td>Una plantilla de cadena</td>
|
||||
<td><code>`pie is ${multiplier} times better than cake`</code></td>
|
||||
<tr>
|
||||
<td>Literal string</td>
|
||||
<td>Cadena literal</td>
|
||||
<td><code>pi</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal number</td>
|
||||
<td>Numero literal</td>
|
||||
<td><code>3.14153265</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal boolean</td>
|
||||
<td>Booleano literal</td>
|
||||
<td><code>true</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal null</td>
|
||||
<td>Nulo literal</td>
|
||||
<td><code>null</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported prefix operator </td>
|
||||
<td>Soporte a operador prefijo</td>
|
||||
<td><code>!cake</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported binary operator </td>
|
||||
<td>Soporte a operaciones binarias</td>
|
||||
<td><code>a+b</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Conditional operator</td>
|
||||
<td>Operador condicional</td>
|
||||
<td><code>a ? b : c</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Parentheses</td>
|
||||
<td>Paréntesis</td>
|
||||
<td><code>(a+b)</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
If an expression uses unsupported syntax, the collector writes an error node to the `.metadata.json` file.
|
||||
The compiler later reports the error if it needs that piece of metadata to generate the application code.
|
||||
Si una expresión usa sintaxis no compatible, el recolector escribe un error de nodo en el archivo `.metadata.json`.
|
||||
El compilador luego reporta el error si necesita esa pieza de metadatos para generar el código de la aplicación.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
If you want `ngc` to report syntax errors immediately rather than produce a `.metadata.json` file with errors, set the `strictMetadataEmit` option in the TypeScript configuration file.
|
||||
Si quieres que `ngc` reporte errores de sintaxis inmediatamente en lugar de producir un archivo `.metadata.json` con errores, configurá la opción `strictMetadataEmit` en el archivo de configuración de TypeScript.
|
||||
|
||||
```
|
||||
"angularCompilerOptions": {
|
||||
@ -220,18 +216,17 @@ The compiler later reports the error if it needs that piece of metadata to gener
|
||||
}
|
||||
```
|
||||
|
||||
Angular libraries have this option to ensure that all Angular `.metadata.json` files are clean and it is a best practice to do the same when building your own libraries.
|
||||
Las librerías de Angular tienen esta opción para asegurar que todo los archivos `.metadata.json` están limpios y es una buena practica hacer lo mismo cuando construimos nuestras propias librerías.
|
||||
|
||||
</div>
|
||||
|
||||
{@a function-expression}
|
||||
{@a arrow-functions}
|
||||
### No arrow functions
|
||||
### Sin funciones flecha
|
||||
|
||||
The AOT compiler does not support [function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)
|
||||
and [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), also called _lambda_ functions.
|
||||
El compilador AOT no soporta [expresiones de función](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function) y [funciones flecha](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function), tampoco las funciones llamadas _lambda_.
|
||||
|
||||
Consider the following component decorator:
|
||||
Considere el siguiente decorador del componente:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
@ -240,11 +235,11 @@ Consider the following component decorator:
|
||||
})
|
||||
```
|
||||
|
||||
The AOT collector does not support the arrow function, `() => new Server()`, in a metadata expression.
|
||||
It generates an error node in place of the function.
|
||||
When the compiler later interprets this node, it reports an error that invites you to turn the arrow function into an _exported function_.
|
||||
El recolector de AOT no soporta la función tipo flecha, `() => new Server()`, en una expression de los metadatos.
|
||||
Esto genera un error de nodo en lugar de la función.
|
||||
Cuando el compilador posteriormente interpreta este nodo, este reporta un error que invita a convertir la función flecha en una _función exportada_.
|
||||
|
||||
You can fix the error by converting to this:
|
||||
Puedes arreglar este error convirtiendo a esto:
|
||||
|
||||
```typescript
|
||||
export function serverFactory() {
|
||||
@ -257,23 +252,23 @@ export function serverFactory() {
|
||||
})
|
||||
```
|
||||
|
||||
In version 5 and later, the compiler automatically performs this rewriting while emitting the `.js` file.
|
||||
En la version 5 y posterior, el compilador realiza automáticamente esta re escritura mientras emite el archivo `.js`.
|
||||
|
||||
{@a exported-symbols}
|
||||
{@a code-folding}
|
||||
### Code folding
|
||||
### Plegado de código (code folding)
|
||||
|
||||
The compiler can only resolve references to **_exported_** symbols.
|
||||
The collector, however, can evaluate an expression during collection and record the result in the `.metadata.json`, rather than the original expression.
|
||||
This allows you to make limited use of non-exported symbols within expressions.
|
||||
El compilador puede solo resolver referencias a símbolos **_exportados_**.
|
||||
El recolector sin embargo, puede evaluar una expresión durante la recolección y registrar el resultado en el `.metadata.json`, en vez de la expresión original.
|
||||
Esto permite hacer un uso limitado de símbolos no exportados dentro de expresiones.
|
||||
|
||||
For example, the collector can evaluate the expression `1 + 2 + 3 + 4` and replace it with the result, `10`.
|
||||
This process is called _folding_. An expression that can be reduced in this manner is _foldable_.
|
||||
Por ejemplo, el recolector puede evaluar la expresión `1 + 2 + 3 + 4` y remplazarlo con el resultado, `10`.
|
||||
El proceso es llamado _plegado_. Una expresión que puede se reducida de esta manera es _plegable_.
|
||||
|
||||
{@a var-declaration}
|
||||
The collector can evaluate references to module-local `const` declarations and initialized `var` and `let` declarations, effectively removing them from the `.metadata.json` file.
|
||||
El recolector puede evaluar referencias hacia el modulo local, declaraciones `const` e inicializadas en `var` y `let` efectivamente son removidas del archivo `.metadata.json`.
|
||||
|
||||
Consider the following component definition:
|
||||
Considere la siguiente definición del componente:
|
||||
|
||||
```typescript
|
||||
const template = '<div>{{hero.name}}</div>';
|
||||
@ -287,9 +282,9 @@ export class HeroComponent {
|
||||
}
|
||||
```
|
||||
|
||||
The compiler could not refer to the `template` constant because it isn't exported.
|
||||
The collector, however, can fold the `template` constant into the metadata definition by in-lining its contents.
|
||||
The effect is the same as if you had written:
|
||||
El compilador no podría referirse hacia la constante `template` por que esta no ha sido exportada.
|
||||
El recolector sim embargo, puede encontrar la constante `template` dentro de la definición de metadatos insertando su contenido.
|
||||
El efecto es el mismo como si hubieras escrito:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
@ -301,9 +296,9 @@ export class HeroComponent {
|
||||
}
|
||||
```
|
||||
|
||||
There is no longer a reference to `template` and, therefore, nothing to trouble the compiler when it later interprets the _collector's_ output in `.metadata.json`.
|
||||
No hay una referencia a `template` y por lo tanto nada que moleste al compilador cuando posteriormente interprete las salidas del recolector en el archivo `.metadata.json`.
|
||||
|
||||
You can take this example a step further by including the `template` constant in another expression:
|
||||
Puedes tomar este ejemplo un paso más allá para incluir la constante `template` en otra expresión:
|
||||
|
||||
```typescript
|
||||
const template = '<div>{{hero.name}}</div>';
|
||||
@ -317,15 +312,15 @@ export class HeroComponent {
|
||||
}
|
||||
```
|
||||
|
||||
The collector reduces this expression to its equivalent _folded_ string:
|
||||
El recolector reduce esta expresión a su equivalente cadena _plegada_:
|
||||
|
||||
```
|
||||
'<div>{{hero.name}}</div><div>{{hero.title}}</div>'
|
||||
```
|
||||
|
||||
#### Foldable syntax
|
||||
#### Sintaxis plegable
|
||||
|
||||
The following table describes which expressions the collector can and cannot fold:
|
||||
La siguiente tabla describe cuales expresiones el recolector puede y no puede encontrar:
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
@ -333,101 +328,101 @@ The following table describes which expressions the collector can and cannot fol
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Syntax</th>
|
||||
<th>Foldable</th>
|
||||
<th>Sintaxis</th>
|
||||
<th>Plegable</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal object </td>
|
||||
<td>yes</td>
|
||||
<td>Objeto literal </td>
|
||||
<td>si</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal array </td>
|
||||
<td>yes</td>
|
||||
<td>Colección literal </td>
|
||||
<td>si</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Spread in literal array</td>
|
||||
<td>Operador spread en colección literal</td>
|
||||
<td>no</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Calls</td>
|
||||
<td>Llamadas</td>
|
||||
<td>no</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>New</td>
|
||||
<td>Nuevo</td>
|
||||
<td>no</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Property access</td>
|
||||
<td>yes, if target is foldable</td>
|
||||
<td>Acceso a propiedades<</td>
|
||||
<td>si, si el objetivo es plegable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Array index</td>
|
||||
<td> yes, if target and index are foldable</td>
|
||||
<td>Indices de colección</td>
|
||||
<td>si, si el objetivo y el indice es plegable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Identity reference</td>
|
||||
<td>yes, if it is a reference to a local</td>
|
||||
<td>Referencia de identidad</td>
|
||||
<td>si, si es una referencia a una local</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>A template with no substitutions</td>
|
||||
<td>yes</td>
|
||||
<td>Una plantilla sin sustituciones</td>
|
||||
<td>si</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>A template with substitutions</td>
|
||||
<td>yes, if the substitutions are foldable</td>
|
||||
<td>Una plantilla con sustituciones</td>
|
||||
<td>si, si las sustituciones son plegables</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal string</td>
|
||||
<td>yes</td>
|
||||
<td>Cadena literal</td>
|
||||
<td>si</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal number</td>
|
||||
<td>yes</td>
|
||||
<td>Numero literal</td>
|
||||
<td>si</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal boolean</td>
|
||||
<td>yes</td>
|
||||
<td>Booleano literal</td>
|
||||
<td>si</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Literal null</td>
|
||||
<td>yes</td>
|
||||
<td>Nulo literal</td>
|
||||
<td>si</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported prefix operator </td>
|
||||
<td>yes, if operand is foldable</td>
|
||||
<td>Soporte a operador prefijo </td>
|
||||
<td>si, si el operador es plegable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Supported binary operator </td>
|
||||
<td>yes, if both left and right are foldable</td>
|
||||
<td>Soporte a operador binario </td>
|
||||
<td>si, si ambos tanto el izquierda y derecha con plegables</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Conditional operator</td>
|
||||
<td>yes, if condition is foldable </td>
|
||||
<td>Operador condicional</td>
|
||||
<td>si, si la condición es plegable </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Parentheses</td>
|
||||
<td>yes, if the expression is foldable</td>
|
||||
<td>Paréntesis</td>
|
||||
<td>si, si la expresión es plegable</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
If an expression is not foldable, the collector writes it to `.metadata.json` as an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) for the compiler to resolve.
|
||||
Si es una expresión no plegable, el recolector lo escribe a `.metadata.json` como un [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) para que el compilador lo resuelva.
|
||||
|
||||
|
||||
## Phase 2: code generation
|
||||
## Fase 2: generación de código
|
||||
|
||||
The collector makes no attempt to understand the metadata that it collects and outputs to `.metadata.json`.
|
||||
It represents the metadata as best it can and records errors when it detects a metadata syntax violation.
|
||||
It's the compiler's job to interpret the `.metadata.json` in the code generation phase.
|
||||
El recolector no hace ningún intento para entender los metadatos que se recolectarón y las envía a `.metadata.json`.
|
||||
Esto representa los metadatos lo mejor que puede y registra errores cuando detecta una violación de sintaxis en los metadatos.
|
||||
Es el trabajo del compilador interpretar el `.metadata.json` en la fase de generación de código.
|
||||
|
||||
The compiler understands all syntax forms that the collector supports, but it may reject _syntactically_ correct metadata if the _semantics_ violate compiler rules.
|
||||
El compilador entiende toda las formas de sintaxis que el recolector soporta pero puede rechazar metadatos _sintácticamente_ correctos si la _semántica_ viola reglas del compilador.
|
||||
|
||||
### Public symbols
|
||||
### Símbolos públicos
|
||||
|
||||
The compiler can only reference _exported symbols_.
|
||||
El compilador puede solo referirse a _símbolos exportados_.
|
||||
|
||||
* Decorated component class members must be public. You cannot make an `@Input()` property private or protected.
|
||||
* Data bound properties must also be public.
|
||||
* Los atributos de la clase que tienen un decorador deben ser públicos. No puedes hacer que una propiedad `@Input()` sea privada o protegida.
|
||||
* Las propiedades enlazadas a datos también deben ser publicas.
|
||||
|
||||
```typescript
|
||||
// BAD CODE - title is private
|
||||
@ -442,32 +437,32 @@ export class AppComponent {
|
||||
|
||||
{@a supported-functions}
|
||||
|
||||
### Supported classes and functions
|
||||
### Clases y funciones compatibles
|
||||
|
||||
The collector can represent a function call or object creation with `new` as long as the syntax is valid.
|
||||
The compiler, however, can later refuse to generate a call to a _particular_ function or creation of a _particular_ object.
|
||||
El recolector puede representar una función o la creación de un objeto con `new` mientras la sintaxis sea valida.
|
||||
El compilador, sin embargo, puede posteriormente rechazar a generar una llamada hacia una función _particular_ o la creación de un objeto _particular_.
|
||||
|
||||
The compiler can only create instances of certain classes, supports only core decorators, and only supports calls to macros (functions or static methods) that return expressions.
|
||||
* New instances
|
||||
El compilador puede solo crea instancias de ciertas clases, compatibles solo con decoradores centrales y solo compatibles con llamadas a macros (funciones o métodos estáticos) que retornan expresiones.
|
||||
|
||||
The compiler only allows metadata that create instances of the class `InjectionToken` from `@angular/core`.
|
||||
* Nuevas instancias
|
||||
El compilador solo permite metadatos que crean instancias de las clases `InjectionToken` de `@angular/core`.
|
||||
|
||||
* Supported decorators
|
||||
* Decoradores soportados
|
||||
El compilador solo soporta metadatos del [Modulo de decoradores de Angular en `@angular/core`](api/core#decorators).
|
||||
|
||||
The compiler only supports metadata for the [Angular decorators in the `@angular/core` module](api/core#decorators).
|
||||
* Llamadas a funciones
|
||||
|
||||
* Function calls
|
||||
|
||||
Factory functions must be exported, named functions.
|
||||
The AOT compiler does not support lambda expressions ("arrow functions") for factory functions.
|
||||
Las funciones de fabrica deben ser exportadas.
|
||||
El compilador AOT no soporta expresiones lambda ("funciones flecha") para las funciones de fabrica.
|
||||
|
||||
{@a function-calls}
|
||||
### Functions and static method calls
|
||||
|
||||
The collector accepts any function or static method that contains a single `return` statement.
|
||||
The compiler, however, only supports macros in the form of functions or static methods that return an *expression*.
|
||||
### Llamadas a funciones y métodos estáticos.
|
||||
|
||||
For example, consider the following function:
|
||||
El recolector acepta cualquier función o método estático que contenga una sola declaración de `return`.
|
||||
El compilador sin embargo, solo soporta macros (funciones o métodos estáticos) en la forma de funciones y métodos estáticos que retornan una *expression*.
|
||||
|
||||
Por ejemplo, considere la siguiente función:
|
||||
|
||||
```typescript
|
||||
export function wrapInArray<T>(value: T): T[] {
|
||||
@ -475,9 +470,9 @@ export function wrapInArray<T>(value: T): T[] {
|
||||
}
|
||||
```
|
||||
|
||||
You can call the `wrapInArray` in a metadata definition because it returns the value of an expression that conforms to the compiler's restrictive JavaScript subset.
|
||||
Puedes llamar a `wrapInArray` en una definición de metadatos porque este retorna el valor de una expresiones qué se ajusta al subconjunto de Javascript restringido del compilador.
|
||||
|
||||
You might use `wrapInArray()` like this:
|
||||
Puede usar `wrapInArray()` así:
|
||||
|
||||
```typescript
|
||||
@NgModule({
|
||||
@ -486,7 +481,7 @@ You might use `wrapInArray()` like this:
|
||||
export class TypicalModule {}
|
||||
```
|
||||
|
||||
The compiler treats this usage as if you had written:
|
||||
El compilador trata este uso como si hubieras escrito:
|
||||
|
||||
```typescript
|
||||
@NgModule({
|
||||
@ -494,19 +489,19 @@ The compiler treats this usage as if you had written:
|
||||
})
|
||||
export class TypicalModule {}
|
||||
```
|
||||
The Angular [`RouterModule`](api/router/RouterModule) exports two macro static methods, `forRoot` and `forChild`, to help declare root and child routes.
|
||||
Review the [source code](https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts#L139 "RouterModule.forRoot source code")
|
||||
for these methods to see how macros can simplify configuration of complex [NgModules](guide/ngmodules).
|
||||
|
||||
El [`RouterModule`](api/router/RouterModule) de Angular exporta dos métodos estáticos, `forRoot` y `forChild` para ayudar a declarar rutas raíz e hijas.
|
||||
Revisa el [código fuente](https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts#L139 "RouterModule.forRoot source code") para estos métodos para ver como los macros puede simplificar la configuración de complejos [NgModules](guide/ngmodules).
|
||||
|
||||
{@a metadata-rewriting}
|
||||
|
||||
### Metadata rewriting
|
||||
### Re escribiendo metadatos
|
||||
|
||||
The compiler treats object literals containing the fields `useClass`, `useValue`, `useFactory`, and `data` specially, converting the expression initializing one of these fields into an exported variable that replaces the expression.
|
||||
This process of rewriting these expressions removes all the restrictions on what can be in them because
|
||||
the compiler doesn't need to know the expression's value—it just needs to be able to generate a reference to the value.
|
||||
El compilador trata a los objetos literales que contengan los campos `useClass`, `useValue`, `useFactory` y `data` específicamente, convirtiendo la expresión inicializando uno de estos campos en una variable exportada que reemplaza la expresión
|
||||
|
||||
You might write something like:
|
||||
Este proceso de rescribir estas expresiones remueve todo las restricciones que pueden estar en el, porque el compilador no necesita conocer el valor de las expresiones solo necesita poder generar una referencia al valor.
|
||||
|
||||
Puedes escribir algo como:
|
||||
|
||||
```typescript
|
||||
class TypicalServer {
|
||||
@ -519,8 +514,8 @@ class TypicalServer {
|
||||
export class TypicalModule {}
|
||||
```
|
||||
|
||||
Without rewriting, this would be invalid because lambdas are not supported and `TypicalServer` is not exported.
|
||||
To allow this, the compiler automatically rewrites this to something like:
|
||||
Sin la reescritura, esto sería invalido por que las lambdas no son soportadas y `TypicalServer` no esta exportada.
|
||||
Para permitirlo, el compilador automáticamente re escribe esto a algo como:
|
||||
|
||||
```typescript
|
||||
class TypicalServer {
|
||||
@ -535,40 +530,38 @@ export const ɵ0 = () => new TypicalServer();
|
||||
export class TypicalModule {}
|
||||
```
|
||||
|
||||
This allows the compiler to generate a reference to `ɵ0` in the factory without having to know what the value of `ɵ0` contains.
|
||||
Esto permite que el compilador genere una referencia hacia `ɵ0` en la fabrica sin tener que conocer cual es el valor de `ɵ0`.
|
||||
|
||||
The compiler does the rewriting during the emit of the `.js` file.
|
||||
It does not, however, rewrite the `.d.ts` file, so TypeScript doesn't recognize it as being an export. and it does not interfere with the ES module's exported API.
|
||||
El compilador hace la reescritura durante la emisión de el archivo `.js`.
|
||||
Sin embargo, no reescribe el archivo `.d.ts`, entonces TypeScript no lo reconoce como una exportación y esto no interfiere con la API exportada de los módulos ES.
|
||||
|
||||
|
||||
{@a binding-expression-validation}
|
||||
|
||||
## Phase 3: Template type checking
|
||||
## Fase 3: Verificación de tipos en las plantillas
|
||||
|
||||
One of the Angular compiler's most helpful features is the ability to type-check expressions within templates, and catch any errors before they cause crashes at runtime.
|
||||
In the template type-checking phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates.
|
||||
Una de las características más útiles del compilador de Angular es la habilidad de comprobar el tipado de las expresiones dentro de las plantillas y capturar cualquier error antes de que ellos causen fallas en tiempo de ejecución.
|
||||
|
||||
Enable this phase explicitly by adding the compiler option `"fullTemplateTypeCheck"` in the `"angularCompilerOptions"` of the project's TypeScript configuration file
|
||||
(see [Angular Compiler Options](guide/angular-compiler-options)).
|
||||
En la fase de verificación de tipos en las plantillas, el compilador de plantillas de Angular usa a el compilador de TypeScript para validar las expresiones con enlazadas a datos en las plantillas.
|
||||
|
||||
Habilite esta fase explícitamente agregando la opción del compilador `"fullTemplateTypeCheck"` en las `"angularCompilerOptions"` del archivo de configuración del proyecto TypeScript (mira [Opciones del compilador de Angular](guide/angular-compiler-options)).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
In [Angular Ivy](guide/ivy), the template type checker has been completely rewritten to be more capable as well as stricter, meaning it can catch a variety of new errors that the previous type checker would not detect.
|
||||
En [Angular Ivy](guide/ivy), la verificación de tipos para las plantillas a sido completamente reescrita para ser más capaz así como más estricto, esto significa poder capturar una variedad de nuevos errores que antes el verificador de tipos no podia detectar.
|
||||
|
||||
As a result, templates that previously compiled under View Engine can fail type checking under Ivy. This can happen because Ivy's stricter checking catches genuine errors, or because application code is not typed correctly, or because the application uses libraries in which typings are inaccurate or not specific enough.
|
||||
Como resultado, las plantillas que previamente se compilarón bajo `View Engine` pueden fallar con el verificador de tipos bajo `Ivy`. Esto puede pasar por que el verificador de Ivy captura errores genuinos o porque el código de la aplicación no esta tipado correctamente o porque la aplicación usa librerías en las cuales el tipado es incorrecto o no es lo suficientemente especifico.
|
||||
|
||||
This stricter type checking is not enabled by default in version 9, but can be enabled by setting the `strictTemplates` configuration option.
|
||||
We do expect to make strict type checking the default in the future.
|
||||
Este verificador de tipos estricto no esta habilitado por defecto el la version 9 pero puedes habilitarlo configurando la opción `strictTemplates`.
|
||||
Nosotros esperamos hacer que el verificador de tipos estricto este habilitado por defecto en el futuro.
|
||||
|
||||
For more information about type-checking options, and about improvements to template type checking in version 9 and above, see [Template type checking](guide/template-typecheck).
|
||||
Para más información acerca de las opciones del verificador de tipos y más acerca de mejoras hacia la verificación de tipos en plantillas en la version 9 en adelante, mira [Verificando tipos en plantillas](guide/template-typecheck).
|
||||
|
||||
</div>
|
||||
|
||||
Template validation produces error messages when a type error is detected in a template binding
|
||||
expression, similar to how type errors are reported by the TypeScript compiler against code in a `.ts`
|
||||
file.
|
||||
La validación de templates produce mensajes de error cuando un error de tipo es detectado en una plantilla con una expresión con enlace de datos, similar a como los errores de tipado son reportados por el compilador de TypeScript contra el código en un archivo `.ts`.
|
||||
|
||||
For example, consider the following component:
|
||||
Por ejemplo, considere el siguiente componente:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
@ -580,32 +573,29 @@ For example, consider the following component:
|
||||
}
|
||||
```
|
||||
|
||||
This produces the following error:
|
||||
Esto produce el siguiente error:
|
||||
|
||||
```
|
||||
my.component.ts.MyComponent.html(1,1): : Property 'addresss' does not exist on type 'Person'. Did you mean 'address'?
|
||||
```
|
||||
|
||||
The file name reported in the error message, `my.component.ts.MyComponent.html`, is a synthetic file
|
||||
generated by the template compiler that holds contents of the `MyComponent` class template.
|
||||
The compiler never writes this file to disk.
|
||||
The line and column numbers are relative to the template string in the `@Component` annotation of the class, `MyComponent` in this case.
|
||||
If a component uses `templateUrl` instead of `template`, the errors are reported in the HTML file referenced by the `templateUrl` instead of a synthetic file.
|
||||
El archivo reporta el mensaje de error, `my.component.ts.MyComponent.html`, es un archivo sintético generado por el compilador de plantillas que espera que tenga contenido de la clase `MyComponent`.
|
||||
El compilador nunca escribe un archivo en el disco.
|
||||
Los números de línea y columna son relativos a la plantilla de cadena en el anotación `@Component` de la clase, `MyComponent` en este caso.
|
||||
Si un componente usa `templateUrl` en vez de `template`, los errores son reportados en el archivo HTML referenciado por el `templateUrl` en vez de un archivo sintético.
|
||||
|
||||
The error location is the beginning of the text node that contains the interpolation expression with the error.
|
||||
If the error is in an attribute binding such as `[value]="person.address.street"`, the error
|
||||
location is the location of the attribute that contains the error.
|
||||
La ubicación del error esta en el inicio del nodo de texto que contiene la expresión interpolada con el error.
|
||||
Si el error esta en un atributo con enlace de datos como `[value]="person.address.street"`, la ubicación del error es la ubicación del atributo que contiene el error.
|
||||
|
||||
La validación usa el verificador de tipos de TypeScript y las opciones suministradas hacia el compilador de TypeScript para controlar qué tan detallada es la validación de tipos.
|
||||
Por ejemplo, si el `strictTypeChecks` es especificado, el error ```my.component.ts.MyComponent.html(1,1): : Object is possibly 'undefined'``` es reportado así como el mensaje de error anterior.
|
||||
|
||||
The validation uses the TypeScript type checker and the options supplied to the TypeScript compiler to control how detailed the type validation is.
|
||||
For example, if the `strictTypeChecks` is specified, the error
|
||||
```my.component.ts.MyComponent.html(1,1): : Object is possibly 'undefined'```
|
||||
is reported as well as the above error message.
|
||||
|
||||
### Type narrowing
|
||||
|
||||
The expression used in an `ngIf` directive is used to narrow type unions in the Angular
|
||||
template compiler, the same way the `if` expression does in TypeScript.
|
||||
For example, to avoid `Object is possibly 'undefined'` error in the template above, modify it to only emit the interpolation if the value of `person` is initialized as shown below:
|
||||
La expresión usada en un directiva `ngIf` es usada para estrechar uniones de tipo en el compilador de plantillas de Angular, de la misma manera que la expresión `if` lo hace en TypeScript.
|
||||
Por ejemplo, para evitar el error `Object is possibly 'undefined'` en la plantilla de arriba, modifícalo para que solo emita la interpolación si el valor de `person` esta inicializado como se muestra en seguida:
|
||||
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
@ -617,16 +607,17 @@ For example, to avoid `Object is possibly 'undefined'` error in the template abo
|
||||
}
|
||||
```
|
||||
|
||||
Using `*ngIf` allows the TypeScript compiler to infer that the `person` used in the binding expression will never be `undefined`.
|
||||
Usando `*ngIf` permite que el compilador de TypeScript infiera que el atributo `person` usado en la expresión enlanzada nunca séra `undefined`.
|
||||
|
||||
For more information about input type narrowing, see [Input setter coercion](guide/template-typecheck#input-setter-coercion) and [Improving template type checking for custom directives](guide/structural-directives#directive-type-checks).
|
||||
Para más información acerca del estrechamiento de tipos de entrada, mira [Coerción del establecedor de entrada](guide/template-typecheck#input-setter-coercion) y [Mejorando el verificar de tipos para directivas personalizadas](guide/structural-directives#directive-type-checks).
|
||||
|
||||
### Non-null type assertion operator
|
||||
### Operador de aserción de tipo nulo
|
||||
|
||||
Use the [non-null type assertion operator](guide/template-expression-operators#non-null-assertion-operator) to suppress the `Object is possibly 'undefined'` error when it is inconvenient to use `*ngIf` or when some constraint in the component ensures that the expression is always non-null when the binding expression is interpolated.
|
||||
Use el [operador de aserción de tipo nulo](guide/template-expression-operators#non-null-assertion-operator) para reprimir el error `Object is possibly 'undefined'` cuando es inconveniente usar `*ngIf` o cuando alguna restricción en el componente asegura que la expresión siempre es no nula cuando la expresión con enlace de datos es interpolada.
|
||||
|
||||
En el siguiente ejemplo, las propiedades `person` y `address` son siempre configuradas juntas, implicando que `address` siempre es no nula si `person` es no nula.
|
||||
No existe una forma conveniente de describir esta restricción a TypeScript y a el compilador de plantillas pero el error es suprimido en el ejemplo por usar `address!.street`.
|
||||
|
||||
In the following example, the `person` and `address` properties are always set together, implying that `address` is always non-null if `person` is non-null.
|
||||
There is no convenient way to describe this constraint to TypeScript and the template compiler, but the error is suppressed in the example by using `address!.street`.
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
@ -644,9 +635,9 @@ There is no convenient way to describe this constraint to TypeScript and the tem
|
||||
}
|
||||
```
|
||||
|
||||
The non-null assertion operator should be used sparingly as refactoring of the component might break this constraint.
|
||||
El operador de aserción de tipo nulo debería usarse con moderación ya que la refactorización del componente podría romper esta restricción.
|
||||
|
||||
In this example it is recommended to include the checking of `address` in the `*ngIf` as shown below:
|
||||
En este ejemplo es recomendable incluir la verificación de `address` en el `*ngIf` como se muestra a continuación:
|
||||
|
||||
```typescript
|
||||
@Component({
|
||||
|
104
aio/content/guide/architecture-modules.en.md
Normal file
104
aio/content/guide/architecture-modules.en.md
Normal file
@ -0,0 +1,104 @@
|
||||
# Introduction to modules
|
||||
|
||||
Angular apps are modular and Angular has its own modularity system called *NgModules*.
|
||||
NgModules are containers for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. They can contain components, service providers, and other code files whose scope is defined by the containing NgModule. They can import functionality that is exported from other NgModules, and export selected functionality for use by other NgModules.
|
||||
|
||||
Every Angular app has at least one NgModule class, [the *root module*](guide/bootstrapping), which is conventionally named `AppModule` and resides in a file named `app.module.ts`. You launch your app by *bootstrapping* the root NgModule.
|
||||
|
||||
While a small application might have only one NgModule, most apps have many more *feature modules*. The *root* NgModule for an app is so named because it can include child NgModules in a hierarchy of any depth.
|
||||
|
||||
## NgModule metadata
|
||||
|
||||
An NgModule is defined by a class decorated with `@NgModule()`. The `@NgModule()` decorator is a function that takes a single metadata object, whose properties describe the module. The most important properties are as follows.
|
||||
|
||||
* `declarations`: The [components](guide/architecture-components), *directives*, and *pipes* that belong to this NgModule.
|
||||
|
||||
* `exports`: The subset of declarations that should be visible and usable in the *component templates* of other NgModules.
|
||||
|
||||
* `imports`: Other modules whose exported classes are needed by component templates declared in *this* NgModule.
|
||||
|
||||
* `providers`: Creators of [services](guide/architecture-services) that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
|
||||
|
||||
* `bootstrap`: The main application view, called the *root component*, which hosts all other app views. Only the *root NgModule* should set the `bootstrap` property.
|
||||
|
||||
Here's a simple root NgModule definition.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="module" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
`AppComponent` is included in the `exports` list here for illustration; it isn't actually necessary in this example. A root NgModule has no reason to *export* anything because other modules don't need to *import* the root NgModule.
|
||||
|
||||
</div>
|
||||
|
||||
## NgModules and components
|
||||
|
||||
NgModules provide a *compilation context* for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/compilation-context.png" alt="Component compilation context" class="left">
|
||||
</div>
|
||||
|
||||
<br class="clear">
|
||||
|
||||
A component and its template together define a *view*. A component can contain a *view hierarchy*, which allows you to define arbitrarily complex areas of the screen that can be created, modified, and destroyed as a unit. A view hierarchy can mix views defined in components that belong to different NgModules. This is often the case, especially for UI libraries.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/view-hierarchy.png" alt="View hierarchy" class="left">
|
||||
</div>
|
||||
|
||||
<br class="clear">
|
||||
|
||||
When you create a component, it's associated directly with a single view, called the *host view*. The host view can be the root of a view hierarchy, which can contain *embedded views*, which are in turn the host views of other components. Those components can be in the same NgModule, or can be imported from other NgModules. Views in the tree can be nested to any depth.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The hierarchical structure of views is a key factor in the way Angular detects and responds to changes in the DOM and app data.
|
||||
|
||||
</div>
|
||||
|
||||
## NgModules and JavaScript modules
|
||||
|
||||
The NgModule system is different from and unrelated to the JavaScript (ES2015) module system for managing collections of JavaScript objects. These are *complementary* module systems that you can use together to write your apps.
|
||||
|
||||
In JavaScript each *file* is a module and all objects defined in the file belong to that module.
|
||||
The module declares some objects to be public by marking them with the `export` key word.
|
||||
Other JavaScript modules use *import statements* to access public objects from other modules.
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="imports"></code-example>
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="export"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
<a href="http://exploringjs.com/es6/ch_modules.html">Learn more about the JavaScript module system on the web.</a>
|
||||
</div>
|
||||
|
||||
## Angular libraries
|
||||
|
||||
<img src="generated/images/guide/architecture/library-module.png" alt="Component" class="left">
|
||||
|
||||
Angular loads as a collection of JavaScript modules. You can think of them as library modules. Each Angular library name begins with the `@angular` prefix. Install them with the node package manager `npm` and import parts of them with JavaScript `import` statements.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
For example, import Angular's `Component` decorator from the `@angular/core` library like this.
|
||||
|
||||
<code-example path="architecture/src/app/app.component.ts" region="import"></code-example>
|
||||
|
||||
You also import NgModules from Angular *libraries* using JavaScript import statements.
|
||||
For example, the following code imports the `BrowserModule` NgModule from the `platform-browser` library.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="import-browser-module"></code-example>
|
||||
|
||||
In the example of the simple root module above, the application module needs material from within
|
||||
`BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="ngmodule-imports"></code-example>
|
||||
|
||||
In this way you're using the Angular and JavaScript module systems *together*. Although it's easy to confuse the two systems, which share the common vocabulary of "imports" and "exports", you will become familiar with the different contexts in which they are used.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Learn more from the [NgModules](guide/ngmodules) guide.
|
||||
|
||||
</div>
|
@ -1,39 +1,39 @@
|
||||
# Introduction to modules
|
||||
# Introducción a módulos
|
||||
|
||||
Angular apps are modular and Angular has its own modularity system called *NgModules*.
|
||||
NgModules are containers for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. They can contain components, service providers, and other code files whose scope is defined by the containing NgModule. They can import functionality that is exported from other NgModules, and export selected functionality for use by other NgModules.
|
||||
Las aplicaciones Angular son modulares y Angular tiene su propio sistema de modularidad llamado *NgModules*.
|
||||
Los NgModules son contenedores para un bloque cohesivo de código dedicado a un dominio de aplicación, un flujo de trabajo o un conjunto de capacidades estrechamente relacionadas. Pueden contener componentes, proveedores de servicios y otros archivos de código cuyo alcance está definido por el NgModule que los contiene. Pueden importar la funcionalidad que se exporta desde otros NgModules y exportar la funcionalidad seleccionada para que la utilicen otros NgModules.
|
||||
|
||||
Every Angular app has at least one NgModule class, [the *root module*](guide/bootstrapping), which is conventionally named `AppModule` and resides in a file named `app.module.ts`. You launch your app by *bootstrapping* the root NgModule.
|
||||
Cada aplicación Angular tiene al menos una clase NgModule, [el *módulo raíz*](guide/bootstrapping), que se llama convencionalmente `AppModule` y reside en un archivo llamado `app.module.ts`. Inicia tu aplicación *cargando* el NgModule raíz.
|
||||
|
||||
While a small application might have only one NgModule, most apps have many more *feature modules*. The *root* NgModule for an app is so named because it can include child NgModules in a hierarchy of any depth.
|
||||
Si bien una aplicación pequeña puede tener sólo un NgModule, la mayoría de las aplicaciones tienen muchos más *módulos de funcionalidad*. El NgModule *raíz* para una aplicación se llama así porque puede incluir NgModules secundarios en una jerarquía de cualquier profundidad.
|
||||
|
||||
## NgModule metadata
|
||||
## Metadatos de NgModule
|
||||
|
||||
An NgModule is defined by a class decorated with `@NgModule()`. The `@NgModule()` decorator is a function that takes a single metadata object, whose properties describe the module. The most important properties are as follows.
|
||||
Un NgModule está definido por una clase decorada con `@NgModule()`. El decorador `@NgModule()` es una función que toma un único objeto de metadatos, cuyas propiedades describen el módulo. Las propiedades más importantes son las siguientes.
|
||||
|
||||
* `declarations`: The [components](guide/architecture-components), *directives*, and *pipes* that belong to this NgModule.
|
||||
* `declarations`: Los [componentes](guide/architecture-components), *directivas*, y *pipes* que pertenecen a este NgModule.
|
||||
|
||||
* `exports`: The subset of declarations that should be visible and usable in the *component templates* of other NgModules.
|
||||
* `exports`: El subconjunto de declaraciones que deberían ser visibles y utilizables en las *plantillas de componentes* de otros NgModules.
|
||||
|
||||
* `imports`: Other modules whose exported classes are needed by component templates declared in *this* NgModule.
|
||||
* `imports`: Otros módulos cuyas clases exportadas son necesarias para las plantillas de componentes declaradas en *este* NgModule.
|
||||
|
||||
* `providers`: Creators of [services](guide/architecture-services) that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
|
||||
* `providers`: Creadores de [servicios](guide/architecture-services) que este NgModule aporta a la colección global de servicios; se vuelven accesibles en todas las partes de la aplicación. (También puedes especificar proveedores a nivel de componente, que a menudo es preferido).
|
||||
|
||||
* `bootstrap`: The main application view, called the *root component*, which hosts all other app views. Only the *root NgModule* should set the `bootstrap` property.
|
||||
* `bootstrap`: La vista principal de la aplicación, llamado el *componente raíz*, que aloja todas las demás vistas de la aplicación. Sólo el *NgModule raíz* debe establecer la propiedad `bootstrap`.
|
||||
|
||||
Here's a simple root NgModule definition.
|
||||
Aquí hay una definición simple del NgModule raíz.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="module" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
`AppComponent` is included in the `exports` list here for illustration; it isn't actually necessary in this example. A root NgModule has no reason to *export* anything because other modules don't need to *import* the root NgModule.
|
||||
Aquí se incluye `AppComponent` en la lista de `exports` como ilustración; en realidad no es necesario en este ejemplo. Un NgModule raíz no tiene ninguna razón para *exportar* nada porque otros módulos no necesitan *importar* el NgModule raíz.
|
||||
|
||||
</div>
|
||||
|
||||
## NgModules and components
|
||||
## NgModules y componentes
|
||||
|
||||
NgModules provide a *compilation context* for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context.
|
||||
NgModules proporciona un *contexto de compilación* para sus componentes. Un NgModule raíz siempre tiene un componente raíz que se crea durante el arranque, pero cualquier NgModule puede incluir cualquier cantidad de componentes adicionales, que se pueden cargar a través del enrutador o crear a través de la plantilla. Los componentes que pertenecen a un NgModule comparten un contexto de compilación.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/compilation-context.png" alt="Component compilation context" class="left">
|
||||
@ -41,7 +41,7 @@ NgModules provide a *compilation context* for their components. A root NgModule
|
||||
|
||||
<br class="clear">
|
||||
|
||||
A component and its template together define a *view*. A component can contain a *view hierarchy*, which allows you to define arbitrarily complex areas of the screen that can be created, modified, and destroyed as a unit. A view hierarchy can mix views defined in components that belong to different NgModules. This is often the case, especially for UI libraries.
|
||||
Juntos, un componente y su plantilla definen una *vista*. Un componente puede contener una *jerarquía de vista*, que te permiten definir áreas arbitrariamente complejas de la pantalla que se pueden crear, modificar y destruir como una unidad. Una jerarquía de vistas puede mezclar vistas definidas en componentes que pertenecen a diferentes NgModules. Este suele ser el caso, especialmente para las bibliotecas de interfaz de usuario.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/view-hierarchy.png" alt="View hierarchy" class="left">
|
||||
@ -49,56 +49,56 @@ A component and its template together define a *view*. A component can contain a
|
||||
|
||||
<br class="clear">
|
||||
|
||||
When you create a component, it's associated directly with a single view, called the *host view*. The host view can be the root of a view hierarchy, which can contain *embedded views*, which are in turn the host views of other components. Those components can be in the same NgModule, or can be imported from other NgModules. Views in the tree can be nested to any depth.
|
||||
Cuando creas un componente, se asocia directamente con una sola vista, llamada *vista host*. La vista host puede ser la raíz de una jerarquía de vistas, que puede contener *vistas incrustadas*, que a su vez son las vistas de host de otros componentes. Esos componentes pueden estar en el mismo NgModule o pueden importarse desde otros NgModules. Las vistas en el árbol se pueden anidar a cualquier profundidad.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The hierarchical structure of views is a key factor in the way Angular detects and responds to changes in the DOM and app data.
|
||||
**Nota:** La estructura jerárquica de las vistas es un factor clave en la forma en que Angular detecta y responde a los cambios en el DOM y los datos de la aplicación.
|
||||
|
||||
</div>
|
||||
|
||||
## NgModules and JavaScript modules
|
||||
## NgModules y módulos JavaScript
|
||||
|
||||
The NgModule system is different from and unrelated to the JavaScript (ES2015) module system for managing collections of JavaScript objects. These are *complementary* module systems that you can use together to write your apps.
|
||||
El sistema NgModule es diferente y no está relacionado con el sistema de módulos JavaScript (ES2015) para administrar colecciones de objetos JavaScript. Estos son sistemas de módulos *complementarios* que puedes usar juntos para escribir tus aplicaciones.
|
||||
|
||||
In JavaScript each *file* is a module and all objects defined in the file belong to that module.
|
||||
The module declares some objects to be public by marking them with the `export` key word.
|
||||
Other JavaScript modules use *import statements* to access public objects from other modules.
|
||||
En JavaScript, cada *archivo* es un módulo y todos los objetos definidos en el archivo pertenecen a ese módulo.
|
||||
El módulo declara que algunos objetos son públicos marcándolos con la palabra clave `export`.
|
||||
Otros módulos de JavaScript usan *declaraciones de importación* para acceder a objetos públicos de otros módulos.
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="imports"></code-example>
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="export"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
<a href="http://exploringjs.com/es6/ch_modules.html">Learn more about the JavaScript module system on the web.</a>
|
||||
<a href="http://exploringjs.com/es6/ch_modules.html">Obtén más información sobre el sistema de módulos de JavaScript en la web.</a>
|
||||
</div>
|
||||
|
||||
## Angular libraries
|
||||
## Bibliotecas Angular
|
||||
|
||||
<img src="generated/images/guide/architecture/library-module.png" alt="Component" class="left">
|
||||
|
||||
Angular loads as a collection of JavaScript modules. You can think of them as library modules. Each Angular library name begins with the `@angular` prefix. Install them with the node package manager `npm` and import parts of them with JavaScript `import` statements.
|
||||
Angular se carga como una colección de módulos JavaScript. Puedes pensar en ellos como módulos de biblioteca. Cada nombre de biblioteca de Angular comienza con el prefijo `@angular`. Instálalos con el gestor de paquetes `npm` e importa partes de ellos con declaraciones `import` de JavaScript.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
For example, import Angular's `Component` decorator from the `@angular/core` library like this.
|
||||
Por ejemplo, importa el decorador `Component` de Angular de la biblioteca `@angular/core` como esta.
|
||||
|
||||
<code-example path="architecture/src/app/app.component.ts" region="import"></code-example>
|
||||
|
||||
You also import NgModules from Angular *libraries* using JavaScript import statements.
|
||||
For example, the following code imports the `BrowserModule` NgModule from the `platform-browser` library.
|
||||
También importa NgModules desde las *bibliotecas* Angular usando declaraciones de importación de JavaScript.
|
||||
Por ejemplo, el siguiente código importa el NgModule `BrowserModule` de la biblioteca `platform-browser`.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="import-browser-module"></code-example>
|
||||
|
||||
In the example of the simple root module above, the application module needs material from within
|
||||
`BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.
|
||||
En el ejemplo del módulo raíz simple anterior, el módulo de la aplicación necesita material de
|
||||
`BrowserModule`. Para acceder a ese material, agrégalo a los metadatos `imports` de `@NgModule` de esta manera.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="ngmodule-imports"></code-example>
|
||||
|
||||
In this way you're using the Angular and JavaScript module systems *together*. Although it's easy to confuse the two systems, which share the common vocabulary of "imports" and "exports", you will become familiar with the different contexts in which they are used.
|
||||
De esta manera, estás utilizando los sistemas de módulos Angular y JavaScript *juntos*. Aunque es fácil confundir los dos sistemas, que comparten el vocabulario común de "importaciones" y "exportaciones", te familiarizarás con los diferentes contextos en los que se utilizan.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Learn more from the [NgModules](guide/ngmodules) guide.
|
||||
Obtén más información en la guía [NgModules](guide/ngmodules).
|
||||
|
||||
</div>
|
||||
|
90
aio/content/guide/architecture-next-steps.en.md
Normal file
90
aio/content/guide/architecture-next-steps.en.md
Normal file
@ -0,0 +1,90 @@
|
||||
# Next steps: tools and techniques
|
||||
|
||||
After you understand the basic Angular building blocks, you can learn more
|
||||
about the features and tools that can help you develop and deliver Angular applications.
|
||||
|
||||
* Work through the [Tour of Heroes](tutorial) tutorial to get a feel for how to fit the basic building blocks together to create a well-designed application.
|
||||
|
||||
* Check out the [Glossary](guide/glossary) to understand Angular-specific terms and usage.
|
||||
|
||||
* Use the documentation to learn about key features in more depth, according to your stage of development and areas of interest.
|
||||
|
||||
## Application architecture
|
||||
|
||||
* The [Components and templates](guide/displaying-data) guide explains how to connect the application data in your [components](guide/glossary#component) to your page-display [templates](guide/glossary#template), to create a complete interactive application.
|
||||
|
||||
* The [NgModules](guide/ngmodules) guide provides in-depth information on the modular structure of an Angular application.
|
||||
|
||||
* The [Routing and navigation](guide/router) guide provides in-depth information on how to construct applications that allow a user to navigate to different [views](guide/glossary#view) within your single-page app.
|
||||
|
||||
* The [Dependency injection](guide/dependency-injection) guide provides in-depth information on how to construct an application such that each component class can acquire the services and objects it needs to perform its function.
|
||||
|
||||
## Responsive programming
|
||||
|
||||
The **Components and Templates** guide provides guidance and details of the [template syntax](guide/template-syntax) that you use to display your component data when and where you want it within a view, and to collect input from users that you can respond to.
|
||||
|
||||
Additional pages and sections describe some basic programming techniques for Angular apps.
|
||||
|
||||
* [Lifecycle hooks](guide/lifecycle-hooks): Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.
|
||||
|
||||
* [Observables and event processing](guide/observables): How to use observables with components and services to publish and subscribe to messages of any type, such as user-interaction events and asynchronous operation results.
|
||||
|
||||
* [Angular elements](guide/elements): How to package components as *custom elements* using Web Components, a web standard for defining new HTML elements in a framework-agnostic way.
|
||||
|
||||
* [Forms](guide/forms-overview): Support complex data entry scenarios with HTML-based input validation.
|
||||
|
||||
* [Animations](guide/animations): Use Angular's animation library to animate component behavior
|
||||
without deep knowledge of animation techniques or CSS.
|
||||
|
||||
## Client-server interaction
|
||||
|
||||
Angular provides a framework for single-page apps, where most of the logic and data resides on the client.
|
||||
Most apps still need to access a server using the `HttpClient` to access and save data.
|
||||
For some platforms and applications, you might also want to use the PWA (Progressive Web App) model to improve the user experience.
|
||||
|
||||
* [HTTP](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
|
||||
|
||||
* [Server-side rendering](guide/universal): Angular Universal generates static application pages on the server through server-side rendering (SSR). This allows you to run your Angular app on the server in order to improve performance and show the first page quickly on mobile and low-powered devices, and also facilitate web crawlers.
|
||||
|
||||
* [Service workers and PWA](guide/service-worker-intro): Use a service worker to reduce dependency on the network and significantly improve the user experience.
|
||||
|
||||
* [Web workers](guide/web-worker): Learn how to run CPU-intensive computations in a background thread.
|
||||
|
||||
## Support for the development cycle
|
||||
|
||||
The **Development Workflow** section describes the tools and processes you use to compile, test, and deploy Angular applications.
|
||||
|
||||
* [CLI Command Reference](cli): The Angular CLI is a command-line tool that you use to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
|
||||
|
||||
* [Compilation](guide/aot-compiler): Angular provides just-in-time (JIT) compilation for the development environment, and ahead-of-time (AOT) compilation for the production environment.
|
||||
|
||||
* [Testing platform](guide/testing): Run unit tests on your application parts as they interact with the Angular framework.
|
||||
|
||||
* [Deployment](guide/deployment): Learn techniques for deploying your Angular application to a remote server.
|
||||
|
||||
* [Security guidelines](guide/security): Learn about Angular's built-in protections against common web-app vulnerabilities and attacks such as cross-site scripting attacks.
|
||||
|
||||
* [Internationalization](guide/i18n): Make your app available in multiple languages with Angular's internationalization (i18n) tools.
|
||||
|
||||
* [Accessibility](guide/accessibility): Make your app accessible to all users.
|
||||
|
||||
|
||||
## File structure, configuration, and dependencies
|
||||
|
||||
* [Workspace and file structure](guide/file-structure): Understand the structure of Angular workspace and project folders.
|
||||
|
||||
* [Building and serving](guide/build): Learn to define different build and proxy server configurations for your project, such as development, staging, and production.
|
||||
|
||||
* [npm packages](guide/npm-packages): The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm](https://docs.npmjs.com/) packages and distributed via the npm registry. The Angular CLI creates a default `package.json` file, which specifies a starter set of packages that work well together and jointly support many common application scenarios.
|
||||
|
||||
* [TypeScript configuration](guide/typescript-configuration): TypeScript is the primary language for Angular application development.
|
||||
|
||||
* [Browser support](guide/browser-support): Make your apps compatible across a wide range of browsers.
|
||||
|
||||
## Extending Angular
|
||||
|
||||
* [Angular libraries](guide/libraries): Learn about using and creating re-usable libraries.
|
||||
|
||||
* [Schematics](guide/schematics): Learn about customizing and extending the CLI's generation capabilities.
|
||||
|
||||
* [CLI builders](guide/cli-builder): Learn about customizing and extending the CLI's ability to apply tools to perform complex tasks, such as building and testing applications.
|
@ -1,90 +1,88 @@
|
||||
# Next steps: tools and techniques
|
||||
# Próximos Pasos: Herramientas y Técnicas
|
||||
|
||||
After you understand the basic Angular building blocks, you can learn more
|
||||
about the features and tools that can help you develop and deliver Angular applications.
|
||||
Una vez que comprendas los conceptos básicos de Angular, puedes aprender más sobre las funcionalidades y herramientas que pueden ayudarte a desarrollar y entregar aplicaciones Angular.
|
||||
|
||||
* Work through the [Tour of Heroes](tutorial) tutorial to get a feel for how to fit the basic building blocks together to create a well-designed application.
|
||||
* Realiza el tutorial [Tour de Héroes](tutorial) para familiarizarte con los conceptos básicos necesarios para crear una aplicación bien diseñada.
|
||||
|
||||
* Check out the [Glossary](guide/glossary) to understand Angular-specific terms and usage.
|
||||
* Consulta el [Glosario](guide/glossary) para comprender los términos específicos de Angular y su correspondiente utilización.
|
||||
|
||||
* Use the documentation to learn about key features in more depth, according to your stage of development and areas of interest.
|
||||
* Utiliza la documentación te permite conocer en detalle las funcionalidades claves, según tu etapa de desarrollo y tus áreas de interés.
|
||||
|
||||
## Application architecture
|
||||
## Arquitectura de la aplicación
|
||||
|
||||
* The [Components and templates](guide/displaying-data) guide explains how to connect the application data in your [components](guide/glossary#component) to your page-display [templates](guide/glossary#template), to create a complete interactive application.
|
||||
* La guía de [Componentes y Plantillas](guide/displaying-data) explica como conectar los datos de la aplicación de sus [componentes](guide/glossary#componente) con las [plantillas](guide/glossary#plantilla) de las pantallas, para crear una aplicación completamente interactiva.
|
||||
|
||||
* The [NgModules](guide/ngmodules) guide provides in-depth information on the modular structure of an Angular application.
|
||||
* La guía de [NgModules](guide/ngmodules) proporciona información detallada sobre la estructura de módulos utilizada en una aplicación Angular.
|
||||
|
||||
* The [Routing and navigation](guide/router) guide provides in-depth information on how to construct applications that allow a user to navigate to different [views](guide/glossary#view) within your single-page app.
|
||||
* La guía de [Enrutamiento y navigación](guide/router) describe como crear aplicaciones que permitan al usuario navegar entre las diferentes [vistas](guide/glossary#vista) dentro de su aplicación de una sola página (SPA).
|
||||
|
||||
* The [Dependency injection](guide/dependency-injection) guide provides in-depth information on how to construct an application such that each component class can acquire the services and objects it needs to perform its function.
|
||||
* La guía de [Injección de dependencias](guide/dependency-injection) brinda información detallada sobre cómo construir una aplicación de modo que cada clase de componente pueda adquirir los servicios y objetos que necesita para realizar su función.
|
||||
|
||||
## Responsive programming
|
||||
## Programación responsive
|
||||
|
||||
The **Components and Templates** guide provides guidance and details of the [template syntax](guide/template-syntax) that you use to display your component data when and where you want it within a view, and to collect input from users that you can respond to.
|
||||
La guía de **Componentes y Plantillas** brinda orientación y detalles de la [sintaxis de plantilla](guide/template-syntax) que se utilizan para mostrar la información de sus componentes, cuando y donde lo desees dentro de una vista y para obtener entradas (inputs) de los usuarios a las que puedas responder.
|
||||
|
||||
Additional pages and sections describe some basic programming techniques for Angular apps.
|
||||
Las páginas y secciones adicionales describen algunas técnicas básicas de programación para aplicaciones Angular.
|
||||
|
||||
* [Lifecycle hooks](guide/lifecycle-hooks): Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.
|
||||
* [Lifecycle Hooks](guide/lifecycle-hooks): Aprovecha los momentos claves de la vida de un componente, desde su creación hasta su destrucción, implementando las interfaces de los `lifecycle hooks`.
|
||||
|
||||
* [Observables and event processing](guide/observables): How to use observables with components and services to publish and subscribe to messages of any type, such as user-interaction events and asynchronous operation results.
|
||||
* [Observables y procesamiento de eventos](guide/observables): Cómo utilizar observables con componentes y servicios para publicar y suscribirse a mensajes de cualquier tipo, tales como los eventos de interacción del usuario y los resultados de operaciones asincrónicas.
|
||||
|
||||
* [Angular elements](guide/elements): How to package components as *custom elements* using Web Components, a web standard for defining new HTML elements in a framework-agnostic way.
|
||||
* [Elementos Angular](guide/elements): Cómo empaquetar componentes como *elementos personalizados* utilizando Web Components, un estándar web para definir nuevos elementos HTML de una manera agnóstica a cualquier framework.
|
||||
|
||||
* [Forms](guide/forms-overview): Support complex data entry scenarios with HTML-based input validation.
|
||||
* [Formularios](guide/forms-overview): Soporta escenarios complejos de entrada de datos con validación de entradas (inputs) basadas en HTML.
|
||||
|
||||
* [Animations](guide/animations): Use Angular's animation library to animate component behavior
|
||||
without deep knowledge of animation techniques or CSS.
|
||||
* [Animaciones](guide/animations): Utiliza la librería de animación de Angular para animar el comportamiento de los componentes sin necesidad de conocer en profundidad las técnicas de animación o CSS.
|
||||
|
||||
## Client-server interaction
|
||||
## Interacción Cliente-Servidor
|
||||
|
||||
Angular provides a framework for single-page apps, where most of the logic and data resides on the client.
|
||||
Most apps still need to access a server using the `HttpClient` to access and save data.
|
||||
For some platforms and applications, you might also want to use the PWA (Progressive Web App) model to improve the user experience.
|
||||
Angular ofrece un framework para aplicaciones de una sola página (SPA), donde la mayoría de la lógica y los datos se encuentran en el cliente.
|
||||
La mayoría de las aplicaciones todavía necesitan acceder a un servidor usando el `HttpClient` para acceder y guardar datos.
|
||||
Para algunas plataformas y aplicaciones, se puede también querer utilizar el modelo PWA (Aplicaciones Web Progresivas) para mejorar la experiencia de usuario.
|
||||
|
||||
* [HTTP](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
|
||||
* [HTTP](guide/http): Comunícate con un servidor para obtener datos, guardarlos e invocar acciones del lado del servidor con un cliente HTTP.
|
||||
|
||||
* [Server-side rendering](guide/universal): Angular Universal generates static application pages on the server through server-side rendering (SSR). This allows you to run your Angular app on the server in order to improve performance and show the first page quickly on mobile and low-powered devices, and also facilitate web crawlers.
|
||||
* [Renderizado del lado del servidor](guide/universal): Angular Universal genera páginas de aplicación estáticas en el servidor a través de la renderización del lado del servidor (SSR). Esto te permite ejecutar tu aplicación Angular en el servidor para mejorar el rendimiento y mostrar la primera página rápidamente en dispositivos móviles y de baja potencia, y también facilitar los rastreadores web.
|
||||
|
||||
* [Service workers and PWA](guide/service-worker-intro): Use a service worker to reduce dependency on the network and significantly improve the user experience.
|
||||
* [Service workers y PWA](guide/service-worker-intro): Utiliza un service worker para reducir la dependencia de la red y mejorar significativamente la experiencia del usuario.
|
||||
|
||||
* [Web workers](guide/web-worker): Learn how to run CPU-intensive computations in a background thread.
|
||||
* [Web workers](guide/web-worker): Aprende a ejecutar cálculos con uso intensivo de la CPU en un hilo en segundo plano.
|
||||
|
||||
## Support for the development cycle
|
||||
## Soporte del Ciclo de Desarrollo
|
||||
|
||||
The **Development Workflow** section describes the tools and processes you use to compile, test, and deploy Angular applications.
|
||||
La sección **Workflow de Desarrollo** detalla las herramientas y los procesos utilizados para compilar, probar y desplegar aplicaciones Angular.
|
||||
|
||||
* [CLI Command Reference](cli): The Angular CLI is a command-line tool that you use to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
|
||||
* [CLI Referencia de Comando](cli): La CLI de Angular es una interfaz de línea de comandos utilizada para crear proyectos, generar código de aplicaciones y librerías y realizar un conjunto de tareas de desarrollo tales como pruebas, empaquetamiento y despliegue de aplicaciones.
|
||||
|
||||
* [Compilation](guide/aot-compiler): Angular provides just-in-time (JIT) compilation for the development environment, and ahead-of-time (AOT) compilation for the production environment.
|
||||
* [Compilación](guide/aot-compiler): Angular proporciona compilación `just-in-time` (JIT) para el entorno de desarrollo y compilación `ahead-of-time` (AOT) para el entorno de producción.
|
||||
|
||||
* [Testing platform](guide/testing): Run unit tests on your application parts as they interact with the Angular framework.
|
||||
* [Plataforma de pruebas](guide/testing): Ejecuta pruebas unitarias sobre las distintas partes de tu aplicación a medida que interactúan con el framework de Angular.
|
||||
|
||||
* [Deployment](guide/deployment): Learn techniques for deploying your Angular application to a remote server.
|
||||
* [Despliegue](guide/deployment): Aprende técnicas para desplegar tu aplicación Angular en un servidor remoto.
|
||||
|
||||
* [Security guidelines](guide/security): Learn about Angular's built-in protections against common web-app vulnerabilities and attacks such as cross-site scripting attacks.
|
||||
* [Lineamientos de Seguridad](guide/security): Aprende sobre las protecciones integradas por Angular contra las vulnerabilidades y los ataques comunes a las aplicaciones web, como por ejemplo, ataques de cross-site scripting.
|
||||
|
||||
* [Internationalization](guide/i18n): Make your app available in multiple languages with Angular's internationalization (i18n) tools.
|
||||
* [Internacionalización](guide/i18n): Haz que tu aplicación soporte múltiples lenguajes con las herramientas de internacionalización de Angular (i18n).
|
||||
|
||||
* [Accessibility](guide/accessibility): Make your app accessible to all users.
|
||||
* [Accesibilidad](guide/accessibility): Haz que tu aplicación sea accesible a todos los usuarios.
|
||||
|
||||
|
||||
## File structure, configuration, and dependencies
|
||||
## Estructura de Archivos, Configuración y Dependencias
|
||||
|
||||
* [Workspace and file structure](guide/file-structure): Understand the structure of Angular workspace and project folders.
|
||||
* [Espacio de trabajo y estructura de archivos](guide/file-structure): Comprende la estructura del espacio de trabajo y las carpetas de proyectos en Angular.
|
||||
|
||||
* [Building and serving](guide/build): Learn to define different build and proxy server configurations for your project, such as development, staging, and production.
|
||||
* [Construcción y servicio](guide/build): Aprende a definir diferentes configuraciones de servidores proxy y construcción para tu proyecto, como por ejemplo desarrollo, staging y producción.
|
||||
|
||||
* [npm packages](guide/npm-packages): The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm](https://docs.npmjs.com/) packages and distributed via the npm registry. The Angular CLI creates a default `package.json` file, which specifies a starter set of packages that work well together and jointly support many common application scenarios.
|
||||
* [Paquetes npm](guide/npm-packages): El Framework de Angular, la CLI de Angular y los componentes usados por las aplicaciones Angular se empaquetan como paquetes [npm](https://docs.npmjs.com/) y se distribuyen a través del registro de `npm`. La CLI de Angular crea por defecto un archivo `package.json`, que especifica un conjunto inicial de paquetes que funcionan bien en conjunto y dan soporte a muchos escenarios de aplicaciones comunes.
|
||||
|
||||
* [TypeScript configuration](guide/typescript-configuration): TypeScript is the primary language for Angular application development.
|
||||
* [Configuración de Typescript](guide/typescript-configuration): TypeScript es el lenguaje principal utilizado para el desarrollo de aplicaciones Angular.
|
||||
|
||||
* [Browser support](guide/browser-support): Make your apps compatible across a wide range of browsers.
|
||||
* [Soporte de Navegadores](guide/browser-support): Haz que tus aplicaciones sean compatibles en una amplia gama de navegadores.
|
||||
|
||||
## Extending Angular
|
||||
## Extendiendo Angular
|
||||
|
||||
* [Angular libraries](guide/libraries): Learn about using and creating re-usable libraries.
|
||||
* [Librerías Angular](guide/libraries): Aprende a usar y crear librerías reutilizables.
|
||||
|
||||
* [Schematics](guide/schematics): Learn about customizing and extending the CLI's generation capabilities.
|
||||
* [Esquemas](guide/schematics): Aprende como personalizar y extender las capacidades de generación de la CLI.
|
||||
|
||||
* [CLI builders](guide/cli-builder): Learn about customizing and extending the CLI's ability to apply tools to perform complex tasks, such as building and testing applications.
|
||||
* [Constructores de la CLI](guide/cli-builder): Aprende a personalizar y extender la capacidad de la CLI de aplicar herramientas para realizar tareas complejas, como la construcción y pruebas de aplicaciones.
|
||||
|
116
aio/content/guide/architecture-services.en.md
Normal file
116
aio/content/guide/architecture-services.en.md
Normal file
@ -0,0 +1,116 @@
|
||||
# Introduction to services and dependency injection
|
||||
|
||||
*Service* is a broad category encompassing any value, function, or feature that an app needs.
|
||||
A service is typically a class with a narrow, well-defined purpose.
|
||||
It should do something specific and do it well.
|
||||
|
||||
Angular distinguishes components from services to increase modularity and reusability.
|
||||
By separating a component's view-related functionality from other kinds of processing,
|
||||
you can make your component classes lean and efficient.
|
||||
|
||||
Ideally, a component's job is to enable the user experience and nothing more.
|
||||
A component should present properties and methods for data binding,
|
||||
in order to mediate between the view (rendered by the template)
|
||||
and the application logic (which often includes some notion of a *model*).
|
||||
|
||||
A component can delegate certain tasks to services, such as fetching data from the server,
|
||||
validating user input, or logging directly to the console.
|
||||
By defining such processing tasks in an *injectable service class*, you make those tasks
|
||||
available to any component.
|
||||
You can also make your app more adaptable by injecting different providers of the same kind of service,
|
||||
as appropriate in different circumstances.
|
||||
|
||||
Angular doesn't *enforce* these principles. Angular does help you *follow* these principles
|
||||
by making it easy to factor your application logic into services and make those services
|
||||
available to components through *dependency injection*.
|
||||
|
||||
## Service examples
|
||||
|
||||
Here's an example of a service class that logs to the browser console.
|
||||
|
||||
<code-example path="architecture/src/app/logger.service.ts" header="src/app/logger.service.ts (class)" region="class"></code-example>
|
||||
|
||||
Services can depend on other services. For example, here's a `HeroService` that depends on the `Logger` service, and also uses `BackendService` to get heroes. That service in turn might depend on the `HttpClient` service to fetch heroes asynchronously from a server.
|
||||
|
||||
<code-example path="architecture/src/app/hero.service.ts" header="src/app/hero.service.ts (class)" region="class"></code-example>
|
||||
|
||||
## Dependency injection (DI)
|
||||
|
||||
<img src="generated/images/guide/architecture/dependency-injection.png" alt="Service" class="left">
|
||||
|
||||
DI is wired into the Angular framework and used everywhere to provide new components with the services or other things they need.
|
||||
Components consume services; that is, you can *inject* a service into a component, giving the component access to that service class.
|
||||
|
||||
To define a class as a service in Angular, use the `@Injectable()` decorator to provide the metadata that allows Angular to inject it into a component as a *dependency*.
|
||||
Similarly, use the `@Injectable()` decorator to indicate that a component or other class (such as another service, a pipe, or an NgModule) *has* a dependency.
|
||||
|
||||
* The *injector* is the main mechanism. Angular creates an application-wide injector for you during the bootstrap process, and additional injectors as needed. You don't have to create injectors.
|
||||
|
||||
* An injector creates dependencies, and maintains a *container* of dependency instances that it reuses if possible.
|
||||
|
||||
* A *provider* is an object that tells an injector how to obtain or create a dependency.
|
||||
|
||||
For any dependency that you need in your app, you must register a provider with the app's injector,
|
||||
so that the injector can use the provider to create new instances.
|
||||
For a service, the provider is typically the service class itself.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
A dependency doesn't have to be a service—it could be a function, for example, or a value.
|
||||
|
||||
</div>
|
||||
|
||||
When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types. For example, the constructor of `HeroListComponent` needs `HeroService`.
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" header="src/app/hero-list.component.ts (constructor)" region="ctor"></code-example>
|
||||
|
||||
When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.
|
||||
|
||||
When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.
|
||||
|
||||
The process of `HeroService` injection looks something like this.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/injector-injects.png" alt="Service" class="left">
|
||||
</div>
|
||||
|
||||
### Providing services
|
||||
|
||||
You must register at least one *provider* of any service you are going to use.
|
||||
The provider can be part of the service's own metadata, making that service available everywhere,
|
||||
or you can register providers with specific modules or components.
|
||||
You register providers in the metadata of the service (in the `@Injectable()` decorator),
|
||||
or in the `@NgModule()` or `@Component()` metadata
|
||||
|
||||
* By default, the Angular CLI command [`ng generate service`](cli/generate) registers a provider with the root injector for your service by including provider metadata in the `@Injectable()` decorator. The tutorial uses this method to register the provider of HeroService class definition.
|
||||
|
||||
```
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
```
|
||||
|
||||
When you provide the service at the root level, Angular creates a single, shared instance of `HeroService`
|
||||
and injects it into any class that asks for it.
|
||||
Registering the provider in the `@Injectable()` metadata also allows Angular to optimize an app
|
||||
by removing the service from the compiled app if it isn't used.
|
||||
|
||||
* When you register a provider with a [specific NgModule](guide/architecture-modules), the same instance of a service is available to all components in that NgModule. To register at this level, use the `providers` property of the `@NgModule()` decorator,
|
||||
|
||||
```
|
||||
@NgModule({
|
||||
providers: [
|
||||
BackendService,
|
||||
Logger
|
||||
],
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
* When you register a provider at the component level, you get a new instance of the
|
||||
service with each new instance of that component.
|
||||
At the component level, register a service provider in the `providers` property of the `@Component()` metadata.
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" header="src/app/hero-list.component.ts (component providers)" region="providers"></code-example>
|
||||
|
||||
For more detailed information, see the [Dependency Injection](guide/dependency-injection) section.
|
@ -1,88 +1,81 @@
|
||||
# Introduction to services and dependency injection
|
||||
# Introducción a servicios e inyección de dependencias
|
||||
|
||||
*Service* is a broad category encompassing any value, function, or feature that an app needs.
|
||||
A service is typically a class with a narrow, well-defined purpose.
|
||||
It should do something specific and do it well.
|
||||
*Servicio* es una categoría amplia que abarca cualquier valor, función o característica que necesite una aplicación.
|
||||
Un servicio es típicamente una clase con un propósito limitado y bien definido.
|
||||
Debe hacer algo específico y hacerlo bien.
|
||||
|
||||
Angular distinguishes components from services to increase modularity and reusability.
|
||||
By separating a component's view-related functionality from other kinds of processing,
|
||||
you can make your component classes lean and efficient.
|
||||
Angular distingue los componentes de los servicios para aumentar la modularidad y la reutilización.
|
||||
Al separar la funcionalidad relacionada con la vista de un componente de otros tipos de procesamiento, puedes hacer que tus componentes sean ágiles y eficientes.
|
||||
|
||||
Ideally, a component's job is to enable the user experience and nothing more.
|
||||
A component should present properties and methods for data binding,
|
||||
in order to mediate between the view (rendered by the template)
|
||||
and the application logic (which often includes some notion of a *model*).
|
||||
Idealmente, el trabajo de un componente es permitir la experiencia del usuario y nada más.
|
||||
Un componente debe presentar propiedades y métodos para el enlace de datos,
|
||||
para mediar entre la vista (representada por la plantilla)
|
||||
y la lógica de la aplicación (que a menudo incluye alguna noción de * modelo *).
|
||||
|
||||
A component can delegate certain tasks to services, such as fetching data from the server,
|
||||
validating user input, or logging directly to the console.
|
||||
By defining such processing tasks in an *injectable service class*, you make those tasks
|
||||
available to any component.
|
||||
You can also make your app more adaptable by injecting different providers of the same kind of service,
|
||||
as appropriate in different circumstances.
|
||||
Un componente puede delegar ciertas tareas a los servicios, como obtener datos del servidor, validar la entrada del usuario o registrar información directamente en la consola.
|
||||
Al definir tales tareas de procesamiento en una * clase de servicio inyectable *, hace que esas tareas sean disponibles para cualquier componente.
|
||||
También puedes hacer que tu aplicación sea más adaptable inyectando diferentes proveedores del mismo tipo de servicio, según corresponda en diferentes circunstancias.
|
||||
|
||||
Angular doesn't *enforce* these principles. Angular does help you *follow* these principles
|
||||
by making it easy to factor your application logic into services and make those services
|
||||
available to components through *dependency injection*.
|
||||
Angular no * impone * estos principios. Angular te ayuda a * seguir * estos principios
|
||||
al facilitar la integración de la lógica de tu aplicación en los servicios y hacer que esos servicios sean disponibles para los componentes a través de * inyección de dependencia *.
|
||||
|
||||
## Service examples
|
||||
## Ejemplos de servicios
|
||||
|
||||
Here's an example of a service class that logs to the browser console.
|
||||
A continuación, se muestra un ejemplo de una clase de servicio que registra información en la consola del navegador.
|
||||
|
||||
<code-example path="architecture/src/app/logger.service.ts" header="src/app/logger.service.ts (class)" region="class"></code-example>
|
||||
|
||||
Services can depend on other services. For example, here's a `HeroService` that depends on the `Logger` service, and also uses `BackendService` to get heroes. That service in turn might depend on the `HttpClient` service to fetch heroes asynchronously from a server.
|
||||
Los servicios pueden depender de otros servicios. Por ejemplo, hay un `HeroService` que depende del `Logger` service, y también usa `BackendService` para obtener héroes. Ese servicio, a su vez, podría depender del servicio `HttpClient` para buscar héroes de forma asíncrona desde un servidor.
|
||||
|
||||
<code-example path="architecture/src/app/hero.service.ts" header="src/app/hero.service.ts (class)" region="class"></code-example>
|
||||
|
||||
## Dependency injection (DI)
|
||||
## Inyección de dependencia (ID)
|
||||
|
||||
<img src="generated/images/guide/architecture/dependency-injection.png" alt="Service" class="left">
|
||||
|
||||
DI is wired into the Angular framework and used everywhere to provide new components with the services or other things they need.
|
||||
Components consume services; that is, you can *inject* a service into a component, giving the component access to that service class.
|
||||
Inyección de dependencia está conectado al framework de Angular y se usa en todas partes para proporcionar nuevos componentes con los servicios u otras cosas que necesitan.
|
||||
Los componentes consumen servicios; es decir, puede * inyectar * un servicio en un componente, dándole acceso al componente a ese servicio.
|
||||
|
||||
To define a class as a service in Angular, use the `@Injectable()` decorator to provide the metadata that allows Angular to inject it into a component as a *dependency*.
|
||||
Similarly, use the `@Injectable()` decorator to indicate that a component or other class (such as another service, a pipe, or an NgModule) *has* a dependency.
|
||||
Para definir una clase como un servicio en Angular, usa el decorador `@Injectable ()` para proporcionar los metadatos que le permitan a Angular inyectarlo en un componente como una * dependencia *.
|
||||
De manera similar, usa el decorador `@Injectable()` para indicar que un componente u otra clase (como otro servicio, un pipeline o un NgModule) * tiene * una dependencia.
|
||||
|
||||
* The *injector* is the main mechanism. Angular creates an application-wide injector for you during the bootstrap process, and additional injectors as needed. You don't have to create injectors.
|
||||
* El * inyector * es el mecanismo principal. Angular crea un inyector para toda la aplicación durante el proceso de arranque e inyectores adicionales según sea necesario. No es necesario crear inyectores.
|
||||
|
||||
* An injector creates dependencies, and maintains a *container* of dependency instances that it reuses if possible.
|
||||
* Un inyector crea dependencias y mantiene un * contenedor * de instancias de dependencia que reutiliza si es posible.
|
||||
|
||||
* A *provider* is an object that tells an injector how to obtain or create a dependency.
|
||||
* Un * proveedor * es un objeto que le dice a un inyector cómo obtener o crear una dependencia.
|
||||
|
||||
For any dependency that you need in your app, you must register a provider with the app's injector,
|
||||
so that the injector can use the provider to create new instances.
|
||||
For a service, the provider is typically the service class itself.
|
||||
Para cualquier dependencia que necesites en tu aplicación, debes registrar un proveedor con el inyector de la aplicación, con el fin de que el inyector pueda utilizar el proveedor para crear nuevas instancias.
|
||||
Para un servicio, el proveedor suele ser la propia clase de servicio.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
A dependency doesn't have to be a service—it could be a function, for example, or a value.
|
||||
Una dependencia no tiene que ser solamente un servicio—podría ser una función, por ejemplo, o un valor.
|
||||
|
||||
</div>
|
||||
|
||||
When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types. For example, the constructor of `HeroListComponent` needs `HeroService`.
|
||||
Cuando Angular crea una nueva instancia de una clase de componente, determina qué servicios u otras dependencias necesita ese componente al observar los tipos de parámetros del constructor. Por ejemplo, el constructor de `HeroListComponent` necesita `HeroService`.
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" header="src/app/hero-list.component.ts (constructor)" region="ctor"></code-example>
|
||||
|
||||
When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.
|
||||
Cuando Angular descubre que un componente depende de un servicio, primero verifica si el inyector tiene instancias existentes de ese servicio. Si una instancia de servicio solicitada aún no existe, el inyector crea una utilizando el proveedor registrado y la agrega al inyector antes de devolver el servicio a Angular.
|
||||
|
||||
When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.
|
||||
Cuando todos los servicios solicitados se han resuelto y devuelto, Angular puede llamar al constructor del componente con esos servicios como argumentos.
|
||||
|
||||
The process of `HeroService` injection looks something like this.
|
||||
El proceso de inyección de "HeroService" se parece a esto.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/injector-injects.png" alt="Service" class="left">
|
||||
</div>
|
||||
|
||||
### Providing services
|
||||
### Proporcionar servicios
|
||||
|
||||
You must register at least one *provider* of any service you are going to use.
|
||||
The provider can be part of the service's own metadata, making that service available everywhere,
|
||||
or you can register providers with specific modules or components.
|
||||
You register providers in the metadata of the service (in the `@Injectable()` decorator),
|
||||
or in the `@NgModule()` or `@Component()` metadata
|
||||
Deberías registrar al menos un * proveedor * de cualquier servicio que vayas a utilizar.
|
||||
El proveedor puede formar parte de los propios metadatos del servicio, haciendo que ese servicio esté disponible en todas partes, o puede registrar proveedores con módulos o componentes específicos.
|
||||
Debes registrar proveedores en los metadatos del servicio (en el decorador `@Injectable()`),
|
||||
o en los metadatos `@NgModule()` o `@Component()`
|
||||
|
||||
* By default, the Angular CLI command [`ng generate service`](cli/generate) registers a provider with the root injector for your service by including provider metadata in the `@Injectable()` decorator. The tutorial uses this method to register the provider of HeroService class definition.
|
||||
* Por defecto, el comando CLI de Angular [`ng generate service`](cli/generate) registra un proveedor con el inyector raíz para tu servicio al incluir metadatos del proveedor en el decorador `@Injectable()`. El tutorial utiliza este método para registrar el proveedor de la definición de clase HeroService.
|
||||
|
||||
```
|
||||
@Injectable({
|
||||
@ -90,12 +83,10 @@ or in the `@NgModule()` or `@Component()` metadata
|
||||
})
|
||||
```
|
||||
|
||||
When you provide the service at the root level, Angular creates a single, shared instance of `HeroService`
|
||||
and injects it into any class that asks for it.
|
||||
Registering the provider in the `@Injectable()` metadata also allows Angular to optimize an app
|
||||
by removing the service from the compiled app if it isn't used.
|
||||
Cuando proporcionas el servicio en el nivel raíz, Angular crea una instancia única compartida de `HeroService` y lo inyecta en cualquier clase que lo solicite.
|
||||
El registro del proveedor en los metadatos `@Injectable()` también permite a Angular optimizar una aplicación eliminando el servicio de la aplicación compilada si no se utiliza.
|
||||
|
||||
* When you register a provider with a [specific NgModule](guide/architecture-modules), the same instance of a service is available to all components in that NgModule. To register at this level, use the `providers` property of the `@NgModule()` decorator,
|
||||
* Cuando registras un proveedor con un [NgModule específico](guide/architecture-modules), la misma instancia de un servicio está disponible para todos los componentes en ese NgModule. Para registrar en este nivel, usa la propiedad `Provider` del decorador `@NgModule()`.
|
||||
|
||||
```
|
||||
@NgModule({
|
||||
@ -107,10 +98,10 @@ or in the `@NgModule()` or `@Component()` metadata
|
||||
})
|
||||
```
|
||||
|
||||
* When you register a provider at the component level, you get a new instance of the
|
||||
service with each new instance of that component.
|
||||
At the component level, register a service provider in the `providers` property of the `@Component()` metadata.
|
||||
* Cuando registras un proveedor a nivel del componente, obtienes una nueva instancia del
|
||||
servicio con cada nueva instancia de ese componente.
|
||||
A nivel del componente, registra un proveedor de servicios en la propiedad `Providers` de los metadatos `@Component()`.
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" header="src/app/hero-list.component.ts (component providers)" region="providers"></code-example>
|
||||
|
||||
For more detailed information, see the [Dependency Injection](guide/dependency-injection) section.
|
||||
Para obtener información más detallada, consulta la sección [Inyección de dependencia](guide/dependency-injection).
|
||||
|
157
aio/content/guide/architecture.en.md
Normal file
157
aio/content/guide/architecture.en.md
Normal file
@ -0,0 +1,157 @@
|
||||
# Introduction to Angular concepts
|
||||
|
||||
Angular is a platform and framework for building single-page client applications using HTML and TypeScript.
|
||||
Angular is written in TypeScript.
|
||||
It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.
|
||||
|
||||
The architecture of an Angular application relies on certain fundamental concepts.
|
||||
The basic building blocks are *NgModules*, which provide a compilation context for *components*. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a *root module* that enables bootstrapping, and typically has many more *feature modules*.
|
||||
|
||||
* Components define *views*, which are sets of screen elements that Angular can choose among and modify according to your program logic and data.
|
||||
|
||||
* Components use *services*, which provide specific functionality not directly related to views. Service providers can be *injected* into components as *dependencies*, making your code modular, reusable, and efficient.
|
||||
|
||||
Modules, components and services are classes that use *decorators*. These decorators mark their type and provide metadata that tells Angular how to use them.
|
||||
|
||||
* The metadata for a component class associates it with a *template* that defines a view. A template combines ordinary HTML with Angular *directives* and *binding markup* that allow Angular to modify the HTML before rendering it for display.
|
||||
|
||||
* The metadata for a service class provides the information Angular needs to make it available to components through *dependency injection (DI)*.
|
||||
|
||||
An app's components typically define many views, arranged hierarchically. Angular provides the `Router` service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the [Angular Glossary](guide/glossary) for basic definitions of important Angular terms and usage.
|
||||
|
||||
</div>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that this page describes, see the <live-example></live-example>.
|
||||
</div>
|
||||
|
||||
## Modules
|
||||
|
||||
Angular *NgModules* differ from and complement JavaScript (ES2015) modules. An NgModule declares a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. An NgModule can associate its components with related code, such as services, to form functional units.
|
||||
|
||||
Every Angular app has a *root module*, conventionally named `AppModule`, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.
|
||||
|
||||
Like JavaScript modules, NgModules can import functionality from other NgModules, and allow their own functionality to be exported and used by other NgModules. For example, to use the router service in your app, you import the `Router` NgModule.
|
||||
|
||||
Organizing your code into distinct functional modules helps in managing development of complex applications, and in designing for reusability. In addition, this technique lets you take advantage of *lazy-loading*—that is, loading modules on demand—to minimize the amount of code that needs to be loaded at startup.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion, see [Introduction to modules](guide/architecture-modules).
|
||||
|
||||
</div>
|
||||
|
||||
## Components
|
||||
|
||||
Every Angular application has at least one component, the *root component* that connects a component hierarchy with the page document object model (DOM). Each component defines a class that contains application data and logic, and is associated with an HTML *template* that defines a view to be displayed in a target environment.
|
||||
|
||||
The `@Component()` decorator identifies the class immediately below it as a component, and provides the template and related component-specific metadata.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Decorators are functions that modify JavaScript classes. Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work.
|
||||
|
||||
<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0">Learn more about decorators on the web.</a>
|
||||
|
||||
</div>
|
||||
|
||||
### Templates, directives, and data binding
|
||||
|
||||
A template combines HTML with Angular markup that can modify HTML elements before they are displayed.
|
||||
Template *directives* provide program logic, and *binding markup* connects your application data and the DOM.
|
||||
There are two types of data binding:
|
||||
|
||||
* *Event binding* lets your app respond to user input in the target environment by updating your application data.
|
||||
* *Property binding* lets you interpolate values that are computed from your application data into the HTML.
|
||||
|
||||
Before a view is displayed, Angular evaluates the directives and resolves the binding syntax in the template to modify the HTML elements and the DOM, according to your program data and logic. Angular supports *two-way data binding*, meaning that changes in the DOM, such as user choices, are also reflected in your program data.
|
||||
|
||||
Your templates can use *pipes* to improve the user experience by transforming values for display.
|
||||
For example, use pipes to display dates and currency values that are appropriate for a user's locale.
|
||||
Angular provides predefined pipes for common transformations, and you can also define your own pipes.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion of these concepts, see [Introduction to components](guide/architecture-components).
|
||||
|
||||
</div>
|
||||
|
||||
{@a dependency-injection}
|
||||
|
||||
|
||||
## Services and dependency injection
|
||||
|
||||
For data or logic that isn't associated with a specific view, and that you want to share across components, you create a *service* class. A service class definition is immediately preceded by the `@Injectable()` decorator. The decorator provides the metadata that allows other providers to be **injected** as dependencies into your class.
|
||||
|
||||
*Dependency injection* (DI) lets you keep your component classes lean and efficient. They don't fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion, see [Introduction to services and DI](guide/architecture-services).
|
||||
|
||||
</div>
|
||||
|
||||
### Routing
|
||||
|
||||
The Angular `Router` NgModule provides a service that lets you define a navigation path among the different application states and view hierarchies in your app. It is modeled on the familiar browser navigation conventions:
|
||||
|
||||
* Enter a URL in the address bar and the browser navigates to a corresponding page.
|
||||
|
||||
* Click links on the page and the browser navigates to a new page.
|
||||
|
||||
* Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.
|
||||
|
||||
The router maps URL-like paths to views instead of pages. When a user performs an action, such as clicking a link, that would load a new page in the browser, the router intercepts the browser's behavior, and shows or hides view hierarchies.
|
||||
|
||||
If the router determines that the current application state requires particular functionality, and the module that defines it hasn't been loaded, the router can *lazy-load* the module on demand.
|
||||
|
||||
The router interprets a link URL according to your app's view navigation rules and data state. You can navigate to new views when the user clicks a button or selects from a drop box, or in response to some other stimulus from any source. The router logs activity in the browser's history, so the back and forward buttons work as well.
|
||||
|
||||
To define navigation rules, you associate *navigation paths* with your components. A path uses a URL-like syntax that integrates your program data, in much the same way that template syntax integrates your views with your program data. You can then apply program logic to choose which views to show or to hide, in response to user input and your own access rules.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion, see [Routing and navigation](guide/router).
|
||||
|
||||
</div>
|
||||
|
||||
<hr/>
|
||||
|
||||
## What's next
|
||||
|
||||
You've learned the basics about the main building blocks of an Angular application. The following diagram shows how these basic pieces are related.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/overview2.png" alt="overview">
|
||||
</div>
|
||||
|
||||
* Together, a component and template define an Angular view.
|
||||
* A decorator on a component class adds the metadata, including a pointer to the associated template.
|
||||
* Directives and binding markup in a component's template modify views based on program data and logic.
|
||||
* The dependency injector provides services to a component, such as the router service that lets you define navigation among views.
|
||||
|
||||
Each of these subjects is introduced in more detail in the following pages.
|
||||
|
||||
* [Introduction to Modules](guide/architecture-modules)
|
||||
|
||||
* [Introduction to Components](guide/architecture-components)
|
||||
|
||||
* [Templates and views](guide/architecture-components#templates-and-views)
|
||||
|
||||
* [Component metadata](guide/architecture-components#component-metadata)
|
||||
|
||||
* [Data binding](guide/architecture-components#data-binding)
|
||||
|
||||
* [Directives](guide/architecture-components#directives)
|
||||
|
||||
* [Pipes](guide/architecture-components#pipes)
|
||||
|
||||
* [Introduction to services and dependency injection](guide/architecture-services)
|
||||
|
||||
When you're familiar with these fundamental building blocks, you can explore them in more detail in the documentation. To learn about more tools and techniques that are available to help you build and deploy Angular applications, see [Next steps: tools and techniques](guide/architecture-next-steps).
|
||||
</div>
|
@ -1,157 +1,157 @@
|
||||
# Introduction to Angular concepts
|
||||
# Introducción a los conceptos de Angular
|
||||
|
||||
Angular is a platform and framework for building single-page client applications using HTML and TypeScript.
|
||||
Angular is written in TypeScript.
|
||||
It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.
|
||||
Angular es una plataforma y un framework para crear aplicaciones de una sola página en el lado del cliente usando HTML y TypeScript.
|
||||
Angular está escrito en TypeScript.
|
||||
Implementa la funcionalidad básica y opcional como un conjunto de bibliotecas TypeScript que importas en tus aplicaciones.
|
||||
|
||||
The architecture of an Angular application relies on certain fundamental concepts.
|
||||
The basic building blocks are *NgModules*, which provide a compilation context for *components*. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a *root module* that enables bootstrapping, and typically has many more *feature modules*.
|
||||
La arquitectura de una aplicación en Angular se basa en ciertos conceptos fundamentales.
|
||||
Los bloques de construcción básicos son los *NgModules*, que proporcionan un contexto de compilación para los *componentes*. Los NgModules recopilan código relacionado en conjuntos funcionales; una aplicación de Angular se define por un conjunto de NgModules. Una aplicación siempre tiene al menos un *módulo raíz* que permite el arranque y generalmente tiene muchos más *módulos de funcionalidad*.
|
||||
|
||||
* Components define *views*, which are sets of screen elements that Angular can choose among and modify according to your program logic and data.
|
||||
* Los componentes definen *vistas*, que son conjuntos de elementos de la pantalla que Angular puede elegir y modificar de acuerdo con la lógica y los datos de tu programa.
|
||||
|
||||
* Components use *services*, which provide specific functionality not directly related to views. Service providers can be *injected* into components as *dependencies*, making your code modular, reusable, and efficient.
|
||||
* Los componentes usan *servicios*, los cuales proporcionan una funcionalidad específica que no está directamente relacionada con las vistas. Los proveedores de servicios pueden *inyectarse* en componentes como *dependencias*, haciendo que tu código sea modular, reutilizable y eficiente.
|
||||
|
||||
Modules, components and services are classes that use *decorators*. These decorators mark their type and provide metadata that tells Angular how to use them.
|
||||
Los módulos, componentes y servicios son clases que usan *decoradores*. Estos decoradores indican su tipo y proporcionan metadatos que le indican a Angular cómo usarlos.
|
||||
|
||||
* The metadata for a component class associates it with a *template* that defines a view. A template combines ordinary HTML with Angular *directives* and *binding markup* that allow Angular to modify the HTML before rendering it for display.
|
||||
* Los metadatos para una clase componente son asociados con una *plantilla* que define una vista. Una plantilla combina HTML ordinario con *directivas* de Angular y *enlace markup* que permiten a Angular modificar el HTML antes de mostrarlo para su visualización.
|
||||
|
||||
* The metadata for a service class provides the information Angular needs to make it available to components through *dependency injection (DI)*.
|
||||
* Los metadatos para una clase servicio proporcionan la información que Angular necesita para que esté disponible para los componentes a través de la *Inyección de Dependencia (ID)*.
|
||||
|
||||
An app's components typically define many views, arranged hierarchically. Angular provides the `Router` service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.
|
||||
Los componentes de una aplicación suelen definir muchas vistas, ordenadas jerárquicamente. Angular proporciona el servicio `Router` para ayudarte a definir rutas de navegación entre vistas. El enrutador proporciona capacidades de navegación sofisticadas en el navegador.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the [Angular Glossary](guide/glossary) for basic definitions of important Angular terms and usage.
|
||||
Visita el [Glosario de Angular](guide/glossary) para ver las definiciones básicas de términos importantes en Angular y su uso.
|
||||
|
||||
</div>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that this page describes, see the <live-example></live-example>.
|
||||
Para ver la aplicación de ejemplo que describe esta página, consulta el <live-example>ejemplo</live-example>.
|
||||
</div>
|
||||
|
||||
## Modules
|
||||
## Módulos
|
||||
|
||||
Angular *NgModules* differ from and complement JavaScript (ES2015) modules. An NgModule declares a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. An NgModule can associate its components with related code, such as services, to form functional units.
|
||||
Los *NgModules* de Angular difieren y complementan los módulos JavaScript (ES2015). Un NgModule declara un contexto de compilación para un conjunto de componentes que está dedicado a un dominio de aplicación, un flujo de trabajo o un conjunto de capacidades estrechamente relacionadas. Un NgModule puede asociar sus componentes con código relacionado, como servicios, para formar unidades funcionales.
|
||||
|
||||
Every Angular app has a *root module*, conventionally named `AppModule`, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.
|
||||
Cada aplicación en Angular tiene un *módulo raíz*, convencionalmente nombrado `AppModule`, que proporciona el mecanismo de arranque que inicia la aplicación. Una aplicación generalmente contiene muchos módulos funcionales.
|
||||
|
||||
Like JavaScript modules, NgModules can import functionality from other NgModules, and allow their own functionality to be exported and used by other NgModules. For example, to use the router service in your app, you import the `Router` NgModule.
|
||||
Como en los módulos de JavaScript, los NgModules pueden importar la funcionalidad de otros, y permiten que su propia funcionalidad sea exportada y utilizada por otros NgModules. Por ejemplo, para utilizar el servicio de enrutamiento en su aplicación, importa el NgModule `Router`.
|
||||
|
||||
Organizing your code into distinct functional modules helps in managing development of complex applications, and in designing for reusability. In addition, this technique lets you take advantage of *lazy-loading*—that is, loading modules on demand—to minimize the amount of code that needs to be loaded at startup.
|
||||
Organizar tu código en distintos módulos funcionales ayuda a gestionar el desarrollo de aplicaciones complejas, y en el diseño para su reutilización. Además, esta técnica te permite aprovechar la *carga diferida*—es decir, cargar módulos bajo demanda—para minimizar la cantidad de código que debe cargarse al inicio.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion, see [Introduction to modules](guide/architecture-modules).
|
||||
Para más información, visita [Introducción a los módulos](guide/architecture-modules).
|
||||
|
||||
</div>
|
||||
|
||||
## Components
|
||||
## Componentes
|
||||
|
||||
Every Angular application has at least one component, the *root component* that connects a component hierarchy with the page document object model (DOM). Each component defines a class that contains application data and logic, and is associated with an HTML *template* that defines a view to be displayed in a target environment.
|
||||
Cada aplicación de Angular tiene al menos un componente, el *componente raíz* que conecta una jerarquía de componentes con el modelo de objetos del documento de la página (DOM). Cada componente define una clase que contiene datos y lógica de la aplicación, y está asociado con una *plantilla* HTML que define una vista que se mostrará en un entorno de destino.
|
||||
|
||||
The `@Component()` decorator identifies the class immediately below it as a component, and provides the template and related component-specific metadata.
|
||||
El decorador `@Component()` identifica la clase inmediatamente debajo de ella como un componente, y proporciona la plantilla y los metadatos específicos del componente relacionado.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Decorators are functions that modify JavaScript classes. Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work.
|
||||
Los decoradores son funciones que modifican las clases de JavaScript. Angular define una serie de decoradores que adjuntan tipos específicos de metadatos a las clases, para que el sistema sepa qué significan esas clases y cómo deberían funcionar.
|
||||
|
||||
<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0">Learn more about decorators on the web.</a>
|
||||
<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0">Obten más información sobre decoradores en la web.</a>
|
||||
|
||||
</div>
|
||||
|
||||
### Templates, directives, and data binding
|
||||
### Plantillas, directivas y enlace de datos
|
||||
|
||||
A template combines HTML with Angular markup that can modify HTML elements before they are displayed.
|
||||
Template *directives* provide program logic, and *binding markup* connects your application data and the DOM.
|
||||
There are two types of data binding:
|
||||
Una plantilla combina HTML con markup de Angular que puede modificar elementos HTML antes de que se muestren.
|
||||
Las *directivas* de la plantilla proporcionan la lógica de programa y el *enlace markup* conecta los datos de tu aplicación y el DOM.
|
||||
Hay dos tipos de enlace de datos:
|
||||
|
||||
* *Event binding* lets your app respond to user input in the target environment by updating your application data.
|
||||
* *Property binding* lets you interpolate values that are computed from your application data into the HTML.
|
||||
* *Manejador de eventos* permite que tu aplicación responda a la entrada del usuario en el entorno objetivo actualizando los datos de tu aplicación.
|
||||
* *Vincular propiedades* te permite interpolar valores que se calculan a partir de los datos de tu aplicación en HTML.
|
||||
|
||||
Before a view is displayed, Angular evaluates the directives and resolves the binding syntax in the template to modify the HTML elements and the DOM, according to your program data and logic. Angular supports *two-way data binding*, meaning that changes in the DOM, such as user choices, are also reflected in your program data.
|
||||
Antes de mostrar una vista, Angular evalúa las directivas y resuelve la sintaxis de enlace en la plantilla para modificar los elementos HTML y el DOM, de acuerdo con los datos y la lógica de tu programa. Angular soporta *enlace de datos en dos sentidos*, lo que significa que los cambios en el DOM, como las elecciones del usuario, también se reflejan en los datos de su programa.
|
||||
|
||||
Your templates can use *pipes* to improve the user experience by transforming values for display.
|
||||
For example, use pipes to display dates and currency values that are appropriate for a user's locale.
|
||||
Angular provides predefined pipes for common transformations, and you can also define your own pipes.
|
||||
Tus plantillas pueden usar *pipes* para mejorar la experiencia del usuario mediante la transformación de valores para mostrar.
|
||||
Por ejemplo, usa pipes para mostrar fechas y valores de moneda que sean apropiados para la configuración regional de un usuario.
|
||||
Angular proporciona pipes predefinidas para transformaciones comunes, y también puedes definir tus propias pipes.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion of these concepts, see [Introduction to components](guide/architecture-components).
|
||||
Para más información sobre estos conceptos, visita [Introducción a los componentes](guide/architecture-components).
|
||||
|
||||
</div>
|
||||
|
||||
{@a dependency-injection}
|
||||
|
||||
|
||||
## Services and dependency injection
|
||||
## Servicios e inyección de dependencia
|
||||
|
||||
For data or logic that isn't associated with a specific view, and that you want to share across components, you create a *service* class. A service class definition is immediately preceded by the `@Injectable()` decorator. The decorator provides the metadata that allows other providers to be **injected** as dependencies into your class.
|
||||
Para los datos o la lógica que no están asociados con una vista específica y que deseas compartir entre componentes, crea una clase *servicio*. Una definición de clase servicio está inmediatamente precedida por el decorador `@Injectable()`. El decorador proporciona los metadatos que permiten **inyectar** otros proveedores como dependencias en su clase.
|
||||
|
||||
*Dependency injection* (DI) lets you keep your component classes lean and efficient. They don't fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.
|
||||
*Inyección de Dependecia* (ID) te permite mantener sus clases componente ligeras y eficientes. No obtienen datos del servidor, validan la entrada del usuario o registra directamente en la consola; tales tareas son delegadas a los servicios.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion, see [Introduction to services and DI](guide/architecture-services).
|
||||
Para más información, visita [Introducción a los servicios e inyección de dependencia](guide/architecture-services).
|
||||
|
||||
</div>
|
||||
|
||||
### Routing
|
||||
### Enrutamiento
|
||||
|
||||
The Angular `Router` NgModule provides a service that lets you define a navigation path among the different application states and view hierarchies in your app. It is modeled on the familiar browser navigation conventions:
|
||||
El NgModule `Router` de Angular proporciona un servicio que te permite definir una ruta de navegación entre los diferentes estados de la aplicación y ver sus jerarquías. Se basa en las convenciones frecuentes de navegación del navegador:
|
||||
|
||||
* Enter a URL in the address bar and the browser navigates to a corresponding page.
|
||||
* Ingresa una URL en la barra de direcciones para que el navegador vaya a la página correspondiente.
|
||||
|
||||
* Click links on the page and the browser navigates to a new page.
|
||||
* Haz clic en los enlaces de la página para que el navegador vaya a una nueva página.
|
||||
|
||||
* Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.
|
||||
* Haz clic en los botones atrás y adelante del navegador para que el navegador vaya hacia atrás y hacia adelante a través del historial de las páginas que has visto.
|
||||
|
||||
The router maps URL-like paths to views instead of pages. When a user performs an action, such as clicking a link, that would load a new page in the browser, the router intercepts the browser's behavior, and shows or hides view hierarchies.
|
||||
El enrutador mapea rutas similares a URL para las vistas en lugar de páginas. Cuando un usuario realiza una acción, como hacer clic en un enlace, que cargaría una nueva página en el navegador, el enrutador intercepta el comportamiento del navegador y muestra u oculta las jerarquías de vista.
|
||||
|
||||
If the router determines that the current application state requires particular functionality, and the module that defines it hasn't been loaded, the router can *lazy-load* the module on demand.
|
||||
Si el enrutador determina que el estado actual de la aplicación requiere una funcionalidad particular, y el módulo que lo define no se ha cargado, el enrutador puede hacer *cargar diferida* sobre el módulo bajo demanda.
|
||||
|
||||
The router interprets a link URL according to your app's view navigation rules and data state. You can navigate to new views when the user clicks a button or selects from a drop box, or in response to some other stimulus from any source. The router logs activity in the browser's history, so the back and forward buttons work as well.
|
||||
El enrutador interpreta una URL de enlace de acuerdo con las reglas de navegación de visualización de la aplicación y el estado de los datos. Puedes navegar a las nuevas vistas cuando el usuario hace clic en un botón o selecciona desde un cuadro desplegable, o en respuesta a algún otro estímulo de cualquier fuente. El enrutador registra la actividad en el historial del navegador, por lo que los botones de retroceso y avance también funcionan.
|
||||
|
||||
To define navigation rules, you associate *navigation paths* with your components. A path uses a URL-like syntax that integrates your program data, in much the same way that template syntax integrates your views with your program data. You can then apply program logic to choose which views to show or to hide, in response to user input and your own access rules.
|
||||
Para definir reglas de navegación, asocia *rutas de navegación* a tus componentes. Una ruta utiliza una sintaxis similar a una URL que integra los datos de tu programa, de la misma manera que la sintaxis de la plantilla integra tus vistas con los datos de tu programa. Luego puedes aplicar la lógica del programa para elegir qué vistas mostrar u ocultar, en respuesta a la entrada del usuario y a tus propias reglas de acceso.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For a more detailed discussion, see [Routing and navigation](guide/router).
|
||||
Para más información, visita [Enrutamiento y navegación](guide/router).
|
||||
|
||||
</div>
|
||||
|
||||
<hr/>
|
||||
|
||||
## What's next
|
||||
## ¿Qué sigue?
|
||||
|
||||
You've learned the basics about the main building blocks of an Angular application. The following diagram shows how these basic pieces are related.
|
||||
Has aprendido los conceptos básicos sobre los bloques de construcción de una aplicación en Angular. El siguiente diagrama muestra cómo se relacionan estos conceptos básicos.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/architecture/overview2.png" alt="overview">
|
||||
</div>
|
||||
|
||||
* Together, a component and template define an Angular view.
|
||||
* A decorator on a component class adds the metadata, including a pointer to the associated template.
|
||||
* Directives and binding markup in a component's template modify views based on program data and logic.
|
||||
* The dependency injector provides services to a component, such as the router service that lets you define navigation among views.
|
||||
* Juntos, un componente y una plantilla definen una vista en Angular.
|
||||
* Un decorador en una clase componente agrega los metadatos, incluido un apuntador a la plantilla asociada.
|
||||
* Las directivas y el enlace markup en la plantilla de un componente modifican las vistas basadas en los datos y la lógica del programa.
|
||||
* El inyector de dependencia proporciona servicios a un componente, como el servicio de enrutamiento que le permite definir la navegación entre vistas.
|
||||
|
||||
Each of these subjects is introduced in more detail in the following pages.
|
||||
Cada uno de estos temas se presenta con más detalle en las siguientes páginas.
|
||||
|
||||
* [Introduction to Modules](guide/architecture-modules)
|
||||
* [Introducción a los Módulos](guide/architecture-modules)
|
||||
|
||||
* [Introduction to Components](guide/architecture-components)
|
||||
* [Introducción a los Componentes](guide/architecture-components)
|
||||
|
||||
* [Templates and views](guide/architecture-components#templates-and-views)
|
||||
* [Plantillas y Vistas](guide/architecture-components#templates-and-views)
|
||||
|
||||
* [Component metadata](guide/architecture-components#component-metadata)
|
||||
* [Metadatos de Componentes](guide/architecture-components#component-metadata)
|
||||
|
||||
* [Data binding](guide/architecture-components#data-binding)
|
||||
* [Enlace de Datos](guide/architecture-components#data-binding)
|
||||
|
||||
* [Directives](guide/architecture-components#directives)
|
||||
* [Directivas](guide/architecture-components#directives)
|
||||
|
||||
* [Pipes](guide/architecture-components#pipes)
|
||||
|
||||
* [Introduction to services and dependency injection](guide/architecture-services)
|
||||
* [Introducción a los Servicios e Inyección de Dependencias.](guide/architecture-services)
|
||||
|
||||
When you're familiar with these fundamental building blocks, you can explore them in more detail in the documentation. To learn about more tools and techniques that are available to help you build and deploy Angular applications, see [Next steps: tools and techniques](guide/architecture-next-steps).
|
||||
Cuando estés familiarizado con estos bloques de construcción fundamentales, podrás explorarlos con más detalle en la documentación. Para saber más acerca de las herramientas y técnicas disponibles para ayudarte a crear y desplegar aplicaciones de Angular, visita [Próximos pasos: herramientas y técnicas](guide/architecture-next-steps).
|
||||
</div>
|
||||
|
303
aio/content/guide/attribute-binding.en.md
Normal file
303
aio/content/guide/attribute-binding.en.md
Normal file
@ -0,0 +1,303 @@
|
||||
# Attribute, class, and style bindings
|
||||
|
||||
The template syntax provides specialized one-way bindings for scenarios less well-suited to property binding.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example></live-example> for a working example containing the code snippets in this guide.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## Attribute binding
|
||||
|
||||
Set the value of an attribute directly with an **attribute binding**. This is the only exception to the rule that a binding sets a target property and the only binding that creates and sets an attribute.
|
||||
|
||||
Usually, setting an element property with a [property binding](guide/property-binding)
|
||||
is preferable to setting the attribute with a string. However, sometimes
|
||||
there is no element property to bind, so attribute binding is the solution.
|
||||
|
||||
Consider the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) and
|
||||
[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG). They are purely attributes, don't correspond to element properties, and don't set element properties. In these cases, there are no property targets to bind to.
|
||||
|
||||
Attribute binding syntax resembles property binding, but
|
||||
instead of an element property between brackets, start with the prefix `attr`,
|
||||
followed by a dot (`.`), and the name of the attribute.
|
||||
You then set the attribute value, using an expression that resolves to a string,
|
||||
or remove the attribute when the expression resolves to `null`.
|
||||
|
||||
One of the primary use cases for attribute binding
|
||||
is to set ARIA attributes, as in this example:
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="attrib-binding-aria" header="src/app/app.component.html"></code-example>
|
||||
|
||||
{@a colspan}
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
#### `colspan` and `colSpan`
|
||||
|
||||
Notice the difference between the `colspan` attribute and the `colSpan` property.
|
||||
|
||||
If you wrote something like this:
|
||||
|
||||
<code-example language="html">
|
||||
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
|
||||
</code-example>
|
||||
|
||||
You'd get this error:
|
||||
|
||||
<code-example language="bash">
|
||||
Template parse errors:
|
||||
Can't bind to 'colspan' since it isn't a known native property
|
||||
</code-example>
|
||||
|
||||
As the message says, the `<td>` element does not have a `colspan` property. This is true
|
||||
because `colspan` is an attribute—`colSpan`, with a capital `S`, is the
|
||||
corresponding property. Interpolation and property binding can set only *properties*, not attributes.
|
||||
|
||||
Instead, you'd use property binding and write it like this:
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="colSpan" header="src/app/app.component.html"></code-example>
|
||||
|
||||
</div>
|
||||
|
||||
<hr/>
|
||||
|
||||
{@a class-binding}
|
||||
|
||||
## Class binding
|
||||
|
||||
Here's how to set the `class` attribute without a binding in plain HTML:
|
||||
|
||||
```html
|
||||
<!-- standard class attribute setting -->
|
||||
<div class="foo bar">Some text</div>
|
||||
```
|
||||
|
||||
You can also add and remove CSS class names from an element's `class` attribute with a **class binding**.
|
||||
|
||||
To create a single class binding, start with the prefix `class` followed by a dot (`.`) and the name of the CSS class (for example, `[class.foo]="hasFoo"`).
|
||||
Angular adds the class when the bound expression is truthy, and it removes the class when the expression is falsy (with the exception of `undefined`, see [styling delegation](#styling-delegation)).
|
||||
|
||||
To create a binding to multiple classes, use a generic `[class]` binding without the dot (for example, `[class]="classExpr"`).
|
||||
The expression can be a space-delimited string of class names, or you can format it as an object with class names as the keys and truthy/falsy expressions as the values.
|
||||
With object format, Angular will add a class only if its associated value is truthy.
|
||||
|
||||
It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated.
|
||||
Updating the property without changing object identity will have no effect.
|
||||
|
||||
If there are multiple bindings to the same class name, conflicts are resolved using [styling precedence](#styling-precedence).
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
</style>
|
||||
|
||||
<table width="100%">
|
||||
<col width="15%">
|
||||
</col>
|
||||
<col width="20%">
|
||||
</col>
|
||||
<col width="35%">
|
||||
</col>
|
||||
<col width="30%">
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Binding Type
|
||||
</th>
|
||||
<th>
|
||||
Syntax
|
||||
</th>
|
||||
<th>
|
||||
Input Type
|
||||
</th>
|
||||
<th>
|
||||
Example Input Values
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Single class binding</td>
|
||||
<td><code>[class.foo]="hasFoo"</code></td>
|
||||
<td><code>boolean | undefined | null</code></td>
|
||||
<td><code>true</code>, <code>false</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan=3>Multi-class binding</td>
|
||||
<td rowspan=3><code>[class]="classExpr"</code></td>
|
||||
<td><code>string</code></td>
|
||||
<td><code>"my-class-1 my-class-2 my-class-3"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>{[key: string]: boolean | undefined | null}</code></td>
|
||||
<td><code>{foo: true, bar: false}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Array</code><<code>string</code>></td>
|
||||
<td><code>['foo', 'bar']</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
The [NgClass](guide/built-in-directives/#ngclass) directive can be used as an alternative to direct `[class]` bindings.
|
||||
However, using the above class binding syntax without `NgClass` is preferred because due to improvements in class binding in Angular, `NgClass` no longer provides significant value, and might eventually be removed in the future.
|
||||
|
||||
|
||||
<hr/>
|
||||
|
||||
## Style binding
|
||||
|
||||
Here's how to set the `style` attribute without a binding in plain HTML:
|
||||
|
||||
```html
|
||||
<!-- standard style attribute setting -->
|
||||
<div style="color: blue">Some text</div>
|
||||
```
|
||||
|
||||
You can also set styles dynamically with a **style binding**.
|
||||
|
||||
To create a single style binding, start with the prefix `style` followed by a dot (`.`) and the name of the CSS style property (for example, `[style.width]="width"`).
|
||||
The property will be set to the value of the bound expression, which is normally a string.
|
||||
Optionally, you can add a unit extension like `em` or `%`, which requires a number type.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Note that a _style property_ name can be written in either
|
||||
[dash-case](guide/glossary#dash-case), as shown above, or
|
||||
[camelCase](guide/glossary#camelcase), such as `fontSize`.
|
||||
|
||||
</div>
|
||||
|
||||
If there are multiple styles you'd like to toggle, you can bind to the `[style]` property directly without the dot (for example, `[style]="styleExpr"`).
|
||||
The expression attached to the `[style]` binding is most often a string list of styles like `"width: 100px; height: 100px;"`.
|
||||
|
||||
You can also format the expression as an object with style names as the keys and style values as the values, like `{width: '100px', height: '100px'}`.
|
||||
It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated.
|
||||
Updating the property without changing object identity will have no effect.
|
||||
|
||||
If there are multiple bindings to the same style property, conflicts are resolved using [styling precedence rules](#styling-precedence).
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
</style>
|
||||
|
||||
<table width="100%">
|
||||
<col width="15%">
|
||||
</col>
|
||||
<col width="20%">
|
||||
</col>
|
||||
<col width="35%">
|
||||
</col>
|
||||
<col width="30%">
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Binding Type
|
||||
</th>
|
||||
<th>
|
||||
Syntax
|
||||
</th>
|
||||
<th>
|
||||
Input Type
|
||||
</th>
|
||||
<th>
|
||||
Example Input Values
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Single style binding</td>
|
||||
<td><code>[style.width]="width"</code></td>
|
||||
<td><code>string | undefined | null</code></td>
|
||||
<td><code>"100px"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<tr>
|
||||
<td>Single style binding with units</td>
|
||||
<td><code>[style.width.px]="width"</code></td>
|
||||
<td><code>number | undefined | null</code></td>
|
||||
<td><code>100</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan=3>Multi-style binding</td>
|
||||
<td rowspan=3><code>[style]="styleExpr"</code></td>
|
||||
<td><code>string</code></td>
|
||||
<td><code>"width: 100px; height: 100px"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>{[key: string]: string | undefined | null}</code></td>
|
||||
<td><code>{width: '100px', height: '100px'}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>Array</code><<code>string</code>></td>
|
||||
<td><code>['width', '100px']</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
The [NgStyle](guide/built-in-directives/#ngstyle) directive can be used as an alternative to direct `[style]` bindings.
|
||||
However, using the above style binding syntax without `NgStyle` is preferred because due to improvements in style binding in Angular, `NgStyle` no longer provides significant value, and might eventually be removed in the future.
|
||||
|
||||
|
||||
<hr/>
|
||||
|
||||
{@a styling-precedence}
|
||||
|
||||
## Styling Precedence
|
||||
|
||||
A single HTML element can have its CSS class list and style values bound to multiple sources (for example, host bindings from multiple directives).
|
||||
|
||||
When there are multiple bindings to the same class name or style property, Angular uses a set of precedence rules to resolve conflicts and determine which classes or styles are ultimately applied to the element.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
<h4>Styling precedence (highest to lowest)</h4>
|
||||
|
||||
1. Template bindings
|
||||
1. Property binding (for example, `<div [class.foo]="hasFoo">` or `<div [style.color]="color">`)
|
||||
1. Map binding (for example, `<div [class]="classExpr">` or `<div [style]="styleExpr">`)
|
||||
1. Static value (for example, `<div class="foo">` or `<div style="color: blue">`)
|
||||
1. Directive host bindings
|
||||
1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`)
|
||||
1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`)
|
||||
1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`)
|
||||
1. Component host bindings
|
||||
1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`)
|
||||
1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`)
|
||||
1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`)
|
||||
|
||||
</div>
|
||||
|
||||
The more specific a class or style binding is, the higher its precedence.
|
||||
|
||||
A binding to a specific class (for example, `[class.foo]`) will take precedence over a generic `[class]` binding, and a binding to a specific style (for example, `[style.bar]`) will take precedence over a generic `[style]` binding.
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="basic-specificity" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Specificity rules also apply when it comes to bindings that originate from different sources.
|
||||
It's possible for an element to have bindings in the template where it's declared, from host bindings on matched directives, and from host bindings on matched components.
|
||||
|
||||
Template bindings are the most specific because they apply to the element directly and exclusively, so they have the highest precedence.
|
||||
|
||||
Directive host bindings are considered less specific because directives can be used in multiple locations, so they have a lower precedence than template bindings.
|
||||
|
||||
Directives often augment component behavior, so host bindings from components have the lowest precedence.
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="source-specificity" header="src/app/app.component.html"></code-example>
|
||||
|
||||
In addition, bindings take precedence over static attributes.
|
||||
|
||||
In the following case, `class` and `[class]` have similar specificity, but the `[class]` binding will take precedence because it is dynamic.
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="dynamic-priority" header="src/app/app.component.html"></code-example>
|
||||
|
||||
{@a styling-delegation}
|
||||
### Delegating to styles with lower precedence
|
||||
|
||||
It is possible for higher precedence styles to "delegate" to lower precedence styles using `undefined` values.
|
||||
Whereas setting a style property to `null` ensures the style is removed, setting it to `undefined` will cause Angular to fall back to the next-highest precedence binding to that style.
|
||||
|
||||
For example, consider the following template:
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="style-delegation" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Imagine that the `dirWithHostBinding` directive and the `comp-with-host-binding` component both have a `[style.width]` host binding.
|
||||
In that case, if `dirWithHostBinding` sets its binding to `undefined`, the `width` property will fall back to the value of the `comp-with-host-binding` host binding.
|
||||
However, if `dirWithHostBinding` sets its binding to `null`, the `width` property will be removed entirely.
|
@ -1,33 +1,28 @@
|
||||
# Attribute, class, and style bindings
|
||||
# Enlaces de atributos, clases y estilos
|
||||
|
||||
The template syntax provides specialized one-way bindings for scenarios less well-suited to property binding.
|
||||
La sintaxis de la plantilla proporciona enlaces one-way especializados para escenarios menos adecuados para el enlace de propiedades.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example></live-example> for a working example containing the code snippets in this guide.
|
||||
Consulta el <live-example></live-example> para ver un ejemplo práctico que contiene los fragmentos de código de esta guía.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## Attribute binding
|
||||
## Enlace de atributo
|
||||
|
||||
Set the value of an attribute directly with an **attribute binding**. This is the only exception to the rule that a binding sets a target property and the only binding that creates and sets an attribute.
|
||||
Establece el valor de un atributo directamente con un **enlace de atributo**. Esta es la única excepción a la regla de que un enlace establece una propiedad de destino y el único enlace que crea y establece un atributo.
|
||||
|
||||
Usually, setting an element property with a [property binding](guide/property-binding)
|
||||
is preferable to setting the attribute with a string. However, sometimes
|
||||
there is no element property to bind, so attribute binding is the solution.
|
||||
Por lo general, establecer una propiedad de elemento con un [enlace de propiedad](guide/property-binding) es preferible establecer el atributo con una string. Sin embargo, a veces
|
||||
no hay ninguna propiedad de elemento para vincular, por lo que la vinculación de atributos es la solución.
|
||||
|
||||
Consider the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) and
|
||||
[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG). They are purely attributes, don't correspond to element properties, and don't set element properties. In these cases, there are no property targets to bind to.
|
||||
Considera el [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) y
|
||||
[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG). Son puramente atributos, no corresponden a las propiedades del elemento y no establecen las propiedades del elemento. En estos casos, no hay objetivos de propiedad a los que vincularse.
|
||||
|
||||
Attribute binding syntax resembles property binding, but
|
||||
instead of an element property between brackets, start with the prefix `attr`,
|
||||
followed by a dot (`.`), and the name of the attribute.
|
||||
You then set the attribute value, using an expression that resolves to a string,
|
||||
or remove the attribute when the expression resolves to `null`.
|
||||
La sintaxis de enlace de atributo se parece al enlace de propiedad, pero en lugar de una propiedad de elemento entre paréntesis, comienza con el prefijo `attr`, seguido de un punto (`.`) y el nombre del atributo.
|
||||
Luego establece el valor del atributo, utilizando una expresión que se resuelve en una string, o elimina el atributo cuando la expresión se resuelva en `null`.
|
||||
|
||||
One of the primary use cases for attribute binding
|
||||
is to set ARIA attributes, as in this example:
|
||||
Uno de los casos de uso principales para el enlace de atributos es establecer atributos ARIA, como en este ejemplo:
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="attrib-binding-aria" header="src/app/app.component.html"></code-example>
|
||||
|
||||
@ -35,28 +30,27 @@ is to set ARIA attributes, as in this example:
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
#### `colspan` and `colSpan`
|
||||
#### `colspan` y `colSpan`
|
||||
|
||||
Notice the difference between the `colspan` attribute and the `colSpan` property.
|
||||
Observa la diferencia entre el atributo `colspan` y la propiedad `colSpan`.
|
||||
|
||||
If you wrote something like this:
|
||||
Si escribes algo como esto:
|
||||
|
||||
<code-example language="html">
|
||||
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
|
||||
</code-example>
|
||||
|
||||
You'd get this error:
|
||||
Recibirías este error:
|
||||
|
||||
<code-example language="bash">
|
||||
Template parse errors:
|
||||
Can't bind to 'colspan' since it isn't a known native property
|
||||
</code-example>
|
||||
|
||||
As the message says, the `<td>` element does not have a `colspan` property. This is true
|
||||
because `colspan` is an attribute—`colSpan`, with a capital `S`, is the
|
||||
corresponding property. Interpolation and property binding can set only *properties*, not attributes.
|
||||
Como dice el mensaje, el elemento `<td>` no tiene una propiedad `colspan`. Esto es verdad
|
||||
porque `colspan` es un atributo—`colSpan`, con una `S` mayúscula, es la propiedad correspondiente. La interpolación y el enlace de propiedades solo pueden establecer *propiedades*, no atributos.
|
||||
|
||||
Instead, you'd use property binding and write it like this:
|
||||
En su lugar, puedes usar el enlace de propiedad y lo escribirías así:
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="colSpan" header="src/app/app.component.html"></code-example>
|
||||
|
||||
@ -66,28 +60,28 @@ Instead, you'd use property binding and write it like this:
|
||||
|
||||
{@a class-binding}
|
||||
|
||||
## Class binding
|
||||
## Enlace de clase
|
||||
|
||||
Here's how to set the `class` attribute without a binding in plain HTML:
|
||||
Aquí se explica cómo configurar el atributo `class` sin un enlace en HTML simple:
|
||||
|
||||
```html
|
||||
<!-- standard class attribute setting -->
|
||||
<div class="foo bar">Some text</div>
|
||||
<div class="foo bar">Algún texto</div>
|
||||
```
|
||||
|
||||
You can also add and remove CSS class names from an element's `class` attribute with a **class binding**.
|
||||
También puedes agregar y eliminar nombres de clase CSS del atributo `class` de un elemento con un **enlace de clase**.
|
||||
|
||||
To create a single class binding, start with the prefix `class` followed by a dot (`.`) and the name of the CSS class (for example, `[class.foo]="hasFoo"`).
|
||||
Angular adds the class when the bound expression is truthy, and it removes the class when the expression is falsy (with the exception of `undefined`, see [styling delegation](#styling-delegation)).
|
||||
Para crear un enlace de clase único, comienza con el prefijo `class` seguido de un punto (`.`) y el nombre de la clase CSS (por ejemplo, `[class.foo]="hasFoo"`).
|
||||
Angular agrega la clase cuando la expresión enlazada es verdadera y elimina la clase cuando la expresión es falsa (con la excepción de `undefined`, vea [delegación de estilo](#styling-delegation)).
|
||||
|
||||
To create a binding to multiple classes, use a generic `[class]` binding without the dot (for example, `[class]="classExpr"`).
|
||||
The expression can be a space-delimited string of class names, or you can format it as an object with class names as the keys and truthy/falsy expressions as the values.
|
||||
With object format, Angular will add a class only if its associated value is truthy.
|
||||
Para crear un enlace a varias clases, usa un enlace genérico `[class]` sin el punto (por ejemplo, `[class]="classExpr"`).
|
||||
La expresión puede ser una string de nombres de clase delimitada por espacios, o puede formatearla como un objeto con nombres de clase como claves y expresiones de verdad / falsedad como valores.
|
||||
Con el formato de objeto, Angular agregará una clase solo si su valor asociado es verdadero.
|
||||
|
||||
It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated.
|
||||
Updating the property without changing object identity will have no effect.
|
||||
Es importante tener en cuenta que con cualquier expresión similar a un objeto (`object`,`Array`, `Map`, `Set`, etc.), la identidad del objeto debe cambiar para que se actualice la lista de clases.
|
||||
Actualizar la propiedad sin cambiar la identidad del objeto no tendrá ningún efecto.
|
||||
|
||||
If there are multiple bindings to the same class name, conflicts are resolved using [styling precedence](#styling-precedence).
|
||||
Si hay varios enlaces al mismo nombre de clase, los conflictos se resuelven usando [precedencia de estilo](#styling-precedence).
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
@ -104,26 +98,26 @@ If there are multiple bindings to the same class name, conflicts are resolved us
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Binding Type
|
||||
Tipo de enlace
|
||||
</th>
|
||||
<th>
|
||||
Syntax
|
||||
Sintaxis
|
||||
</th>
|
||||
<th>
|
||||
Input Type
|
||||
Tipo de entrada
|
||||
</th>
|
||||
<th>
|
||||
Example Input Values
|
||||
Ejemplo de valores de entrada
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Single class binding</td>
|
||||
<td>Enlace de clase única</td>
|
||||
<td><code>[class.foo]="hasFoo"</code></td>
|
||||
<td><code>boolean | undefined | null</code></td>
|
||||
<td><code>true</code>, <code>false</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan=3>Multi-class binding</td>
|
||||
<td rowspan=3>Enlace de clases múltiples</td>
|
||||
<td rowspan=3><code>[class]="classExpr"</code></td>
|
||||
<td><code>string</code></td>
|
||||
<td><code>"my-class-1 my-class-2 my-class-3"</code></td>
|
||||
@ -139,43 +133,43 @@ If there are multiple bindings to the same class name, conflicts are resolved us
|
||||
</table>
|
||||
|
||||
|
||||
The [NgClass](guide/built-in-directives/#ngclass) directive can be used as an alternative to direct `[class]` bindings.
|
||||
However, using the above class binding syntax without `NgClass` is preferred because due to improvements in class binding in Angular, `NgClass` no longer provides significant value, and might eventually be removed in the future.
|
||||
La directiva [NgClass](guide/built-in-directives/#ngclass) se puede utilizar como alternativa a los enlaces directos `[class]`.
|
||||
Sin embargo, se prefiere usar la sintaxis de enlace de clase anterior sin `NgClass` porque debido a las mejoras en el enlace de clase en Angular, `NgClass` ya no proporciona un valor significativo y podría eliminarse en el futuro.
|
||||
|
||||
|
||||
<hr/>
|
||||
|
||||
## Style binding
|
||||
{@a style-binding}
|
||||
|
||||
Here's how to set the `style` attribute without a binding in plain HTML:
|
||||
## Enlace de estilo
|
||||
|
||||
Aquí se explica cómo configurar el atributo `style` sin un enlace en HTML simple:
|
||||
|
||||
```html
|
||||
<!-- standard style attribute setting -->
|
||||
<div style="color: blue">Some text</div>
|
||||
<div style="color: blue">Algún texto</div>
|
||||
```
|
||||
|
||||
You can also set styles dynamically with a **style binding**.
|
||||
También se puede establecer estilos dinámicamente con un **enlace de estilo**.
|
||||
|
||||
To create a single style binding, start with the prefix `style` followed by a dot (`.`) and the name of the CSS style property (for example, `[style.width]="width"`).
|
||||
The property will be set to the value of the bound expression, which is normally a string.
|
||||
Optionally, you can add a unit extension like `em` or `%`, which requires a number type.
|
||||
Para crear un enlace de estilo único, comienza con el prefijo `style` seguido de un punto (`.`) y el nombre de la propiedad de estilo CSS (por ejemplo, `[style.width]="width"`).
|
||||
La propiedad se establecerá en el valor de la expresión enlazada, que normalmente es una string.
|
||||
Opcionalmente, se puede agregar una extensión de unidad como `em` o `%`, que requiere un tipo de número.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Note that a _style property_ name can be written in either
|
||||
[dash-case](guide/glossary#dash-case), as shown above, or
|
||||
[camelCase](guide/glossary#camelcase), such as `fontSize`.
|
||||
Ten en cuenta que se puede escribir una _propiedad de estilo_ en [dash-case](guide/glossary#dash-case), como se muestra arriba, o [camelCase](guide/glossary#camelcase), como `fontSize`.
|
||||
|
||||
</div>
|
||||
|
||||
If there are multiple styles you'd like to toggle, you can bind to the `[style]` property directly without the dot (for example, `[style]="styleExpr"`).
|
||||
The expression attached to the `[style]` binding is most often a string list of styles like `"width: 100px; height: 100px;"`.
|
||||
Si deseas alternar múltiples estilos, puedes vincular la propiedad `[style]` directamente sin el punto (por ejemplo, `[style]="styleExpr"`).
|
||||
La expresión asociada al enlace `[style]` suele ser una lista de string de estilos como `"width: 100px; height: 100px;"`.
|
||||
|
||||
You can also format the expression as an object with style names as the keys and style values as the values, like `{width: '100px', height: '100px'}`.
|
||||
It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated.
|
||||
Updating the property without changing object identity will have no effect.
|
||||
También se puede formatear la expresión como un objeto con nombres de estilo como claves y valores de estilo como los valores, como `{width: '100px', height: '100px'}`.
|
||||
Es importante tener en cuenta que con cualquier expresión similar a un objeto (`object`, `Array`, `Map`, `Set`, etc), la identidad del objeto debe cambiar para que se actualice la lista de clases.
|
||||
Actualizar la propiedad sin cambiar la identidad del objeto no tendrá ningún efecto.
|
||||
|
||||
If there are multiple bindings to the same style property, conflicts are resolved using [styling precedence rules](#styling-precedence).
|
||||
Si hay varios enlaces a la misma propiedad de estilo, los conflictos se resuelven usando [reglas de precedencia de estilo](#styling-precedence).
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
@ -192,33 +186,33 @@ If there are multiple bindings to the same style property, conflicts are resolve
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Binding Type
|
||||
Tipo de enlace
|
||||
</th>
|
||||
<th>
|
||||
Syntax
|
||||
Sintaxis
|
||||
</th>
|
||||
<th>
|
||||
Input Type
|
||||
Tipo de entrada
|
||||
</th>
|
||||
<th>
|
||||
Example Input Values
|
||||
Ejemplo de valores de entrada
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Single style binding</td>
|
||||
<td>Enlace de estilo único</td>
|
||||
<td><code>[style.width]="width"</code></td>
|
||||
<td><code>string | undefined | null</code></td>
|
||||
<td><code>"100px"</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<tr>
|
||||
<td>Single style binding with units</td>
|
||||
<td>Enlace de estilo único con unidades</td>
|
||||
<td><code>[style.width.px]="width"</code></td>
|
||||
<td><code>number | undefined | null</code></td>
|
||||
<td><code>100</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan=3>Multi-style binding</td>
|
||||
<td rowspan=3>Enlace de múltiples estilos</td>
|
||||
<td rowspan=3><code>[style]="styleExpr"</code></td>
|
||||
<td><code>string</code></td>
|
||||
<td><code>"width: 100px; height: 100px"</code></td>
|
||||
@ -233,71 +227,71 @@ If there are multiple bindings to the same style property, conflicts are resolve
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
The [NgStyle](guide/built-in-directives/#ngstyle) directive can be used as an alternative to direct `[style]` bindings.
|
||||
However, using the above style binding syntax without `NgStyle` is preferred because due to improvements in style binding in Angular, `NgStyle` no longer provides significant value, and might eventually be removed in the future.
|
||||
La directiva [NgStyle](guide/built-in-directives/#ngstyle) se puede utilizar como alternativa a los enlaces directos `[style]`.
|
||||
Sin embargo, se prefiere usar la sintaxis de enlace de estilos anterior sin `NgStyle` porque debido a las mejoras en el enlace de estilos en Angular, `NgStyle` ya no proporciona un valor significativo y podría eliminarse en el futuro.
|
||||
|
||||
|
||||
<hr/>
|
||||
|
||||
{@a styling-precedence}
|
||||
|
||||
## Styling Precedence
|
||||
## Precedencia de estilo
|
||||
|
||||
A single HTML element can have its CSS class list and style values bound to multiple sources (for example, host bindings from multiple directives).
|
||||
Un único elemento HTML puede tener su lista de clases CSS y valores de estilo vinculados a múltiples fuentes (por ejemplo, enlaces de host de múltiples directivas).
|
||||
|
||||
When there are multiple bindings to the same class name or style property, Angular uses a set of precedence rules to resolve conflicts and determine which classes or styles are ultimately applied to the element.
|
||||
Cuando hay varios enlaces al mismo nombre de clase o propiedad de estilo, Angular usa un conjunto de reglas de precedencia para resolver conflictos y determinar qué clases o estilos se aplican finalmente al elemento.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
<h4>Styling precedence (highest to lowest)</h4>
|
||||
<h4>Precedencia de estilo (de mayor a menor)</h4>
|
||||
|
||||
1. Template bindings
|
||||
1. Property binding (for example, `<div [class.foo]="hasFoo">` or `<div [style.color]="color">`)
|
||||
1. Map binding (for example, `<div [class]="classExpr">` or `<div [style]="styleExpr">`)
|
||||
1. Static value (for example, `<div class="foo">` or `<div style="color: blue">`)
|
||||
1. Directive host bindings
|
||||
1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`)
|
||||
1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`)
|
||||
1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`)
|
||||
1. Component host bindings
|
||||
1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`)
|
||||
1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`)
|
||||
1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`)
|
||||
1. Enlaces de plantillas
|
||||
1. Enlace de propiedad (por ejemplo, `<div [class.foo]="hasFoo">` o `<div [style.color]="color">`)
|
||||
1. Enlace de mapa (por ejemplo, `<div [class]="classExpr">` o `<div [style]="styleExpr">`)
|
||||
1. Valor estático (por ejemplo, `<div class="foo">` o `<div style="color: blue">`)
|
||||
1. Enlaces de directivas hosts
|
||||
1. Enlace de propiedad (por ejemplo, `host: {'[class.foo]': 'hasFoo'}` o `host: {'[style.color]': 'color'}`)
|
||||
1. Enlace de mapa (por ejemplo, `host: {'[class]': 'classExpr'}` o `host: {'[style]': 'styleExpr'}`)
|
||||
1. Valor estático (por ejemplo, `host: {'class': 'foo'}` o `host: {'style': 'color: blue'}`)
|
||||
1. Enlaces de componentes hosts
|
||||
1. Enlace de propiedad (por ejemplo, `host: {'[class.foo]': 'hasFoo'}` o `host: {'[style.color]': 'color'}`)
|
||||
1. Enlace de mapa (por ejemplo, `host: {'[class]': 'classExpr'}` o `host: {'[style]': 'styleExpr'}`)
|
||||
1. Valor estático (por ejemplo, `host: {'class': 'foo'}` o `host: {'style': 'color: blue'}`)
|
||||
|
||||
</div>
|
||||
|
||||
The more specific a class or style binding is, the higher its precedence.
|
||||
Cuanto más específico sea un enlace de clase o estilo, mayor será su precedencia.
|
||||
|
||||
A binding to a specific class (for example, `[class.foo]`) will take precedence over a generic `[class]` binding, and a binding to a specific style (for example, `[style.bar]`) will take precedence over a generic `[style]` binding.
|
||||
Un enlace a una clase específica (por ejemplo, `[class.foo]`) tendrá prioridad sobre un enlace genérico `[class]`, y un enlace a un estilo específico (por ejemplo, `[style.bar]`) tendrá prioridad sobre un enlace genérico `[style]`.
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="basic-specificity" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Specificity rules also apply when it comes to bindings that originate from different sources.
|
||||
It's possible for an element to have bindings in the template where it's declared, from host bindings on matched directives, and from host bindings on matched components.
|
||||
Las reglas de especificidad también se aplican cuando se trata de enlaces que se originan de diferentes fuentes.
|
||||
Es posible que un elemento tenga enlaces en la plantilla donde se declara, desde enlaces de host en directivas coincidentes y desde enlaces de host en componentes coincidentes.
|
||||
|
||||
Template bindings are the most specific because they apply to the element directly and exclusively, so they have the highest precedence.
|
||||
Los enlaces de plantilla son los más específicos porque se aplican al elemento directa y exclusivamente, por lo que tienen la mayor prioridad.
|
||||
|
||||
Directive host bindings are considered less specific because directives can be used in multiple locations, so they have a lower precedence than template bindings.
|
||||
Los enlaces de host de directiva se consideran menos específicos porque las directivas se pueden usar en varias ubicaciones, por lo que tienen una precedencia menor que los enlaces de plantilla.
|
||||
|
||||
Directives often augment component behavior, so host bindings from components have the lowest precedence.
|
||||
Las directivas a menudo aumentan el comportamiento de los componentes, por lo que los enlaces de host de los componentes tienen la prioridad más baja.
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="source-specificity" header="src/app/app.component.html"></code-example>
|
||||
|
||||
In addition, bindings take precedence over static attributes.
|
||||
Además, los enlaces tienen prioridad sobre los atributos estáticos.
|
||||
|
||||
In the following case, `class` and `[class]` have similar specificity, but the `[class]` binding will take precedence because it is dynamic.
|
||||
En el siguiente caso, `class` y `[class]` tienen una especificidad similar, pero el enlace `[class]` tendrá prioridad porque es dinámico.
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="dynamic-priority" header="src/app/app.component.html"></code-example>
|
||||
|
||||
{@a styling-delegation}
|
||||
### Delegating to styles with lower precedence
|
||||
### Delegar a estilos con menor prioridad
|
||||
|
||||
It is possible for higher precedence styles to "delegate" to lower precedence styles using `undefined` values.
|
||||
Whereas setting a style property to `null` ensures the style is removed, setting it to `undefined` will cause Angular to fall back to the next-highest precedence binding to that style.
|
||||
Es posible que los estilos de precedencia más alta "deleguen" a los estilos de precedencia más bajos utilizando valores `undefined`.
|
||||
Mientras que establecer una propiedad de estilo en `null` asegura que el estilo se elimine, establecerlo en `undefined` hará que Angular vuelva al siguiente enlace de precedencia más alto para ese estilo.
|
||||
|
||||
For example, consider the following template:
|
||||
Por ejemplo, considera la siguiente plantilla:
|
||||
|
||||
<code-example path="attribute-binding/src/app/app.component.html" region="style-delegation" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Imagine that the `dirWithHostBinding` directive and the `comp-with-host-binding` component both have a `[style.width]` host binding.
|
||||
In that case, if `dirWithHostBinding` sets its binding to `undefined`, the `width` property will fall back to the value of the `comp-with-host-binding` host binding.
|
||||
However, if `dirWithHostBinding` sets its binding to `null`, the `width` property will be removed entirely.
|
||||
Imagina que la directiva `dirWithHostBinding` y el componente `comp-with-host-binding` tienen un enlace de host `[style.width]`.
|
||||
En ese caso, si `dirWithHostBinding` establece su enlace en `undefined`, la propiedad `width` volverá al valor del enlace de host del componente `comp-with-host-binding`.
|
||||
Sin embargo, si `dirWithHostBinding` establece su enlace en `null`, la propiedad `width` se eliminará por completo.
|
||||
|
318
aio/content/guide/binding-syntax.en.md
Normal file
318
aio/content/guide/binding-syntax.en.md
Normal file
@ -0,0 +1,318 @@
|
||||
|
||||
# Binding syntax: an overview
|
||||
|
||||
Data-binding is a mechanism for coordinating what users see, specifically
|
||||
with application data values.
|
||||
While you could push values to and pull values from HTML,
|
||||
the application is easier to write, read, and maintain if you turn these tasks over to a binding framework.
|
||||
You simply declare bindings between binding sources, target HTML elements, and let the framework do the rest.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example></live-example> for a working example containing the code snippets in this guide.
|
||||
|
||||
</div>
|
||||
|
||||
Angular provides many kinds of data-binding. Binding types can be grouped into three categories distinguished by the direction of data flow:
|
||||
|
||||
* From the _source-to-view_
|
||||
* From _view-to-source_
|
||||
* Two-way sequence: _view-to-source-to-view_
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
</style>
|
||||
|
||||
<table width="100%">
|
||||
<col width="30%">
|
||||
</col>
|
||||
<col width="50%">
|
||||
</col>
|
||||
<col width="20%">
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Type
|
||||
</th>
|
||||
<th>
|
||||
Syntax
|
||||
</th>
|
||||
<th>
|
||||
Category
|
||||
</th>
|
||||
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Interpolation<br>
|
||||
Property<br>
|
||||
Attribute<br>
|
||||
Class<br>
|
||||
Style
|
||||
</td>
|
||||
<td>
|
||||
|
||||
<code-example>
|
||||
{{expression}}
|
||||
[target]="expression"
|
||||
bind-target="expression"
|
||||
</code-example>
|
||||
|
||||
</td>
|
||||
|
||||
<td>
|
||||
One-way<br>from data source<br>to view target
|
||||
</td>
|
||||
<tr>
|
||||
<td>
|
||||
Event
|
||||
</td>
|
||||
<td>
|
||||
<code-example>
|
||||
(target)="statement"
|
||||
on-target="statement"
|
||||
</code-example>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
One-way<br>from view target<br>to data source
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Two-way
|
||||
</td>
|
||||
<td>
|
||||
<code-example>
|
||||
[(target)]="expression"
|
||||
bindon-target="expression"
|
||||
</code-example>
|
||||
</td>
|
||||
<td>
|
||||
Two-way
|
||||
</td>
|
||||
</tr>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
Binding types other than interpolation have a **target name** to the left of the equal sign, either surrounded by punctuation, `[]` or `()`,
|
||||
or preceded by a prefix: `bind-`, `on-`, `bindon-`.
|
||||
|
||||
The *target* of a binding is the property or event inside the binding punctuation: `[]`, `()` or `[()]`.
|
||||
|
||||
Every public member of a **source** directive is automatically available for binding.
|
||||
You don't have to do anything special to access a directive member in a template expression or statement.
|
||||
|
||||
|
||||
### Data-binding and HTML
|
||||
|
||||
In the normal course of HTML development, you create a visual structure with HTML elements, and
|
||||
you modify those elements by setting element attributes with string constants.
|
||||
|
||||
```html
|
||||
<div class="special">Plain old HTML</div>
|
||||
<img src="images/item.png">
|
||||
<button disabled>Save</button>
|
||||
```
|
||||
|
||||
With data-binding, you can control things like the state of a button:
|
||||
|
||||
<code-example path="binding-syntax/src/app/app.component.html" region="disabled-button" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Notice that the binding is to the `disabled` property of the button's DOM element,
|
||||
**not** the attribute. This applies to data-binding in general. Data-binding works with *properties* of DOM elements, components, and directives, not HTML *attributes*.
|
||||
|
||||
{@a html-attribute-vs-dom-property}
|
||||
|
||||
### HTML attribute vs. DOM property
|
||||
|
||||
The distinction between an HTML attribute and a DOM property is key to understanding
|
||||
how Angular binding works. **Attributes are defined by HTML. Properties are accessed from DOM (Document Object Model) nodes.**
|
||||
|
||||
* A few HTML attributes have 1:1 mapping to properties; for example, `id`.
|
||||
|
||||
* Some HTML attributes don't have corresponding properties; for example, `aria-*`.
|
||||
|
||||
* Some DOM properties don't have corresponding attributes; for example, `textContent`.
|
||||
|
||||
It is important to remember that *HTML attribute* and the *DOM property* are different things, even when they have the same name.
|
||||
In Angular, the only role of HTML attributes is to initialize element and directive state.
|
||||
|
||||
**Template binding works with *properties* and *events*, not *attributes*.**
|
||||
|
||||
When you write a data-binding, you're dealing exclusively with the *DOM properties* and *events* of the target object.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
This general rule can help you build a mental model of attributes and DOM properties:
|
||||
**Attributes initialize DOM properties and then they are done.
|
||||
Property values can change; attribute values can't.**
|
||||
|
||||
There is one exception to this rule.
|
||||
Attributes can be changed by `setAttribute()`, which re-initializes corresponding DOM properties.
|
||||
|
||||
</div>
|
||||
|
||||
For more information, see the [MDN Interfaces documentation](https://developer.mozilla.org/en-US/docs/Web/API#Interfaces) which has API docs for all the standard DOM elements and their properties.
|
||||
Comparing the [`<td>` attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td) attributes to the [`<td>` properties](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) provides a helpful example for differentiation.
|
||||
In particular, you can navigate from the attributes page to the properties via "DOM interface" link, and navigate the inheritance hierarchy up to `HTMLTableCellElement`.
|
||||
|
||||
|
||||
#### Example 1: an `<input>`
|
||||
|
||||
When the browser renders `<input type="text" value="Sarah">`, it creates a
|
||||
corresponding DOM node with a `value` property initialized to "Sarah".
|
||||
|
||||
```html
|
||||
<input type="text" value="Sarah">
|
||||
```
|
||||
|
||||
When the user enters "Sally" into the `<input>`, the DOM element `value` *property* becomes "Sally".
|
||||
However, if you look at the HTML attribute `value` using `input.getAttribute('value')`, you can see that the *attribute* remains unchanged—it returns "Sarah".
|
||||
|
||||
The HTML attribute `value` specifies the *initial* value; the DOM `value` property is the *current* value.
|
||||
|
||||
To see attributes versus DOM properties in a functioning app, see the <live-example name="binding-syntax"></live-example> especially for binding syntax.
|
||||
|
||||
#### Example 2: a disabled button
|
||||
|
||||
The `disabled` attribute is another example. A button's `disabled`
|
||||
*property* is `false` by default so the button is enabled.
|
||||
|
||||
When you add the `disabled` *attribute*, its presence alone
|
||||
initializes the button's `disabled` *property* to `true`
|
||||
so the button is disabled.
|
||||
|
||||
```html
|
||||
<button disabled>Test Button</button>
|
||||
```
|
||||
|
||||
Adding and removing the `disabled` *attribute* disables and enables the button.
|
||||
However, the value of the *attribute* is irrelevant,
|
||||
which is why you cannot enable a button by writing `<button disabled="false">Still Disabled</button>`.
|
||||
|
||||
To control the state of the button, set the `disabled` *property*,
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Though you could technically set the `[attr.disabled]` attribute binding, the values are different in that the property binding requires to a boolean value, while its corresponding attribute binding relies on whether the value is `null` or not. Consider the following:
|
||||
|
||||
```html
|
||||
<input [disabled]="condition ? true : false">
|
||||
<input [attr.disabled]="condition ? 'disabled' : null">
|
||||
```
|
||||
|
||||
Generally, use property binding over attribute binding as it is more intuitive (being a boolean value), has a shorter syntax, and is more performant.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
To see the `disabled` button example in a functioning app, see the <live-example name="binding-syntax"></live-example> especially for binding syntax. This example shows you how to toggle the disabled property from the component.
|
||||
|
||||
## Binding types and targets
|
||||
|
||||
The **target of a data-binding** is something in the DOM.
|
||||
Depending on the binding type, the target can be a property (element, component, or directive),
|
||||
an event (element, component, or directive), or sometimes an attribute name.
|
||||
The following table summarizes the targets for the different binding types.
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
</style>
|
||||
|
||||
<table width="100%">
|
||||
<col width="10%">
|
||||
</col>
|
||||
<col width="15%">
|
||||
</col>
|
||||
<col width="75%">
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Type
|
||||
</th>
|
||||
<th>
|
||||
Target
|
||||
</th>
|
||||
<th>
|
||||
Examples
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Property
|
||||
</td>
|
||||
<td>
|
||||
Element property<br>
|
||||
Component property<br>
|
||||
Directive property
|
||||
</td>
|
||||
<td>
|
||||
<code>src</code>, <code>hero</code>, and <code>ngClass</code> in the following:
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="property-binding-syntax-1"></code-example>
|
||||
<!-- For more information, see [Property Binding](guide/property-binding). -->
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Event
|
||||
</td>
|
||||
<td>
|
||||
Element event<br>
|
||||
Component event<br>
|
||||
Directive event
|
||||
</td>
|
||||
<td>
|
||||
<code>click</code>, <code>deleteRequest</code>, and <code>myClick</code> in the following:
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="event-binding-syntax-1"></code-example>
|
||||
<!-- KW--Why don't these links work in the table? -->
|
||||
<!-- <div>For more information, see [Event Binding](guide/event-binding).</div> -->
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Two-way
|
||||
</td>
|
||||
<td>
|
||||
Event and property
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="2-way-binding-syntax-1"></code-example>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Attribute
|
||||
</td>
|
||||
<td>
|
||||
Attribute
|
||||
(the exception)
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="attribute-binding-syntax-1"></code-example>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Class
|
||||
</td>
|
||||
<td>
|
||||
<code>class</code> property
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="class-binding-syntax-1"></code-example>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Style
|
||||
</td>
|
||||
<td>
|
||||
<code>style</code> property
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="style-binding-syntax-1"></code-example>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
@ -1,23 +1,21 @@
|
||||
|
||||
# Binding syntax: an overview
|
||||
# Sintaxis de Enlace: una visión general
|
||||
|
||||
Data-binding is a mechanism for coordinating what users see, specifically
|
||||
with application data values.
|
||||
While you could push values to and pull values from HTML,
|
||||
the application is easier to write, read, and maintain if you turn these tasks over to a binding framework.
|
||||
You simply declare bindings between binding sources, target HTML elements, and let the framework do the rest.
|
||||
El enlace de datos es un mecanismo utilizado para coordinar los valores de los datos que los usuarios visualizan en la aplicación.
|
||||
Aunque puedas insertar y actualizar valores en el HTML, la aplicación es más fácil de escribir, leer y mantener si tu le dejas esas tareas al framework de enlace.
|
||||
Por lo que simplemente debes declarar enlaces entre los datos del modelo y los elementos HTML y dejar al framework que haga el resto del trabajo.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example></live-example> for a working example containing the code snippets in this guide.
|
||||
Consulta la <live-example>aplicación de muestra</live-example> que es un ejemplo funcional que contiene los fragmentos de código utilizados en esta guía.
|
||||
|
||||
</div>
|
||||
|
||||
Angular provides many kinds of data-binding. Binding types can be grouped into three categories distinguished by the direction of data flow:
|
||||
Angular proporciona muchas formas para manejar el enlace de datos. Los tipos de enlace se pueden agrupar en tres categorías que se distinguen de acuerdo a la dirección del flujo de datos:
|
||||
|
||||
* From the _source-to-view_
|
||||
* From _view-to-source_
|
||||
* Two-way sequence: _view-to-source-to-view_
|
||||
* Desde el _modelo-hacia-vista_
|
||||
* Desde la _vista-hacia-modelo_
|
||||
* Secuencia Bidireccional: _vista-hacia-modelo-hacia-vista_
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
@ -32,23 +30,23 @@ Angular provides many kinds of data-binding. Binding types can be grouped into t
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Type
|
||||
Tipo
|
||||
</th>
|
||||
<th>
|
||||
Syntax
|
||||
Sintaxis
|
||||
</th>
|
||||
<th>
|
||||
Category
|
||||
Categoría
|
||||
</th>
|
||||
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Interpolation<br>
|
||||
Property<br>
|
||||
Attribute<br>
|
||||
Class<br>
|
||||
Style
|
||||
Interpolación<br>
|
||||
Propiedad<br>
|
||||
Atributo<br>
|
||||
Clase<br>
|
||||
Estilos
|
||||
</td>
|
||||
<td>
|
||||
|
||||
@ -61,11 +59,11 @@ Angular provides many kinds of data-binding. Binding types can be grouped into t
|
||||
</td>
|
||||
|
||||
<td>
|
||||
One-way<br>from data source<br>to view target
|
||||
Una sola dirección<br>desde el modelo de datos<br>hacia la vista
|
||||
</td>
|
||||
<tr>
|
||||
<td>
|
||||
Event
|
||||
Evento
|
||||
</td>
|
||||
<td>
|
||||
<code-example>
|
||||
@ -75,12 +73,12 @@ Angular provides many kinds of data-binding. Binding types can be grouped into t
|
||||
</td>
|
||||
|
||||
<td>
|
||||
One-way<br>from view target<br>to data source
|
||||
Una sola dirección<br>desde la vista<br>hacia el modelo de datos
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Two-way
|
||||
Bidireccional
|
||||
</td>
|
||||
<td>
|
||||
<code-example>
|
||||
@ -89,132 +87,123 @@ Angular provides many kinds of data-binding. Binding types can be grouped into t
|
||||
</code-example>
|
||||
</td>
|
||||
<td>
|
||||
Two-way
|
||||
Bidireccional
|
||||
</td>
|
||||
</tr>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
Binding types other than interpolation have a **target name** to the left of the equal sign, either surrounded by punctuation, `[]` or `()`,
|
||||
or preceded by a prefix: `bind-`, `on-`, `bindon-`.
|
||||
Los tipos de enlace distintos a la interporlación tienen un **nombre de destino** hacia la izquierda del signo igual, están rodeados por los signos de puntación `[]` o `()`, o bien están precedidos por el prefijo: `bind-`, `on-`, `bindon-`.
|
||||
|
||||
The *target* of a binding is the property or event inside the binding punctuation: `[]`, `()` or `[()]`.
|
||||
El *destino* de un enlace es la propiedad o evento situado dentro de los signos de puntuación: `[]`, `()` or `[()]`.
|
||||
|
||||
Every public member of a **source** directive is automatically available for binding.
|
||||
You don't have to do anything special to access a directive member in a template expression or statement.
|
||||
Cada miembro <span class="x x-first x-last">público</span> de una directiva **fuente** <span class="x x-first x-last">está</span> disponible automaticamente para ser utilizada con los enlaces.
|
||||
No es necesario hacer nada especial para poder acceder al miembro de una directiva en una expresión o declaración de plantilla.
|
||||
|
||||
### Enlace de Datos y el HTML
|
||||
|
||||
### Data-binding and HTML
|
||||
|
||||
In the normal course of HTML development, you create a visual structure with HTML elements, and
|
||||
you modify those elements by setting element attributes with string constants.
|
||||
En condiciones normales para un desarrollo HTML, primero se crea la estructura visual con los elementos HTML y luego se modifican dichos elementos estableciendo los atributos de dichos elementos utilizando una cadena de caracteres.
|
||||
|
||||
```html
|
||||
<div class="special">Plain old HTML</div>
|
||||
<div class="special">HTML Simple</div>
|
||||
<img src="images/item.png">
|
||||
<button disabled>Save</button>
|
||||
<button disabled>Guardar</button>
|
||||
```
|
||||
|
||||
With data-binding, you can control things like the state of a button:
|
||||
Usando el enlace de datos, puedes controlar cosas como el estado de un botón:
|
||||
|
||||
<code-example path="binding-syntax/src/app/app.component.html" region="disabled-button" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Notice that the binding is to the `disabled` property of the button's DOM element,
|
||||
**not** the attribute. This applies to data-binding in general. Data-binding works with *properties* of DOM elements, components, and directives, not HTML *attributes*.
|
||||
Puedes notar que el enlace se realiza a la propiedad `disabled` del elemento botón del DOM,
|
||||
**no** al atributo. Esto aplica al enlace de datos en general. El enlace de datos funciona con las *propiedades* de los elementos, componentes y directivas del DOM, no con los *atributos* HTML
|
||||
|
||||
{@a html-attribute-vs-dom-property}
|
||||
|
||||
### HTML attribute vs. DOM property
|
||||
### Atributos HTML vs. Propiedades del DOM
|
||||
|
||||
The distinction between an HTML attribute and a DOM property is key to understanding
|
||||
how Angular binding works. **Attributes are defined by HTML. Properties are accessed from DOM (Document Object Model) nodes.**
|
||||
Distinguir la diferencia entre un atributo HTML y una propiedad del DOM es clave para comprender como funciona el enlace en Angular. **Los attributos son definidos por el HTML. Las propiedades se acceden desde los nodos del DOM (Document Object Model).**
|
||||
|
||||
* A few HTML attributes have 1:1 mapping to properties; for example, `id`.
|
||||
* Muy pocos atributos HTML tienen una relación 1:1 con las propiedades; por ejemplo el, `id`.
|
||||
|
||||
* Some HTML attributes don't have corresponding properties; for example, `aria-*`.
|
||||
* Algunos atributos HTML no tienen su correspondencia en propiedades; como por ejemplo, `aria-*`.
|
||||
|
||||
* Some DOM properties don't have corresponding attributes; for example, `textContent`.
|
||||
* Algunas propiedades del DOM no tienen su correspondencia hacia atributos; como por ejemplo, `textContent`.
|
||||
|
||||
It is important to remember that *HTML attribute* and the *DOM property* are different things, even when they have the same name.
|
||||
In Angular, the only role of HTML attributes is to initialize element and directive state.
|
||||
Es importante recordar que los *atributos HTML* y las *propiedades del DOM* son cosas muy diferentes, incluso cuando tienen el mismo nombre.
|
||||
En Angular, el único rol de los atributos HTML es el de inicializar el estado de los elementos y las directivas.
|
||||
|
||||
**Template binding works with *properties* and *events*, not *attributes*.**
|
||||
**El enlace de plantilla funciona con *propiedades* y *eventos*, no con *atributos*.**
|
||||
|
||||
When you write a data-binding, you're dealing exclusively with the *DOM properties* and *events* of the target object.
|
||||
Cuando escribes un enlace de datos, se trata exclusivamente sobre las *propiedades del DOM* and *eventos* del objeto de destino.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
This general rule can help you build a mental model of attributes and DOM properties:
|
||||
**Attributes initialize DOM properties and then they are done.
|
||||
Property values can change; attribute values can't.**
|
||||
Esta regla general puede ayudarnos a crear un modelo mental de los atributos y las propiedades del DOM:
|
||||
**Los atributos inicializan las propiedades del DOM y cuando eso ya esta hecho, los valores de las propiedades pueden cambiar, mientras que los atributos no lo pueden hacer.**
|
||||
|
||||
There is one exception to this rule.
|
||||
Attributes can be changed by `setAttribute()`, which re-initializes corresponding DOM properties.
|
||||
Solamente hay una excepción a la regla.
|
||||
Los atributos pueden cambiarse usando el método `setAttribute()`, el cual re-inicializa las propiedades del DOM correspondientes.
|
||||
|
||||
</div>
|
||||
|
||||
For more information, see the [MDN Interfaces documentation](https://developer.mozilla.org/en-US/docs/Web/API#Interfaces) which has API docs for all the standard DOM elements and their properties.
|
||||
Comparing the [`<td>` attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td) attributes to the [`<td>` properties](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) provides a helpful example for differentiation.
|
||||
In particular, you can navigate from the attributes page to the properties via "DOM interface" link, and navigate the inheritance hierarchy up to `HTMLTableCellElement`.
|
||||
Para más información, consulta la [Documentación de Interfaces MDN](https://developer.mozilla.org/en-US/docs/Web/API#Interfaces) que contiene los documentos de la API para todos los elementos estándar del DOM y sus propiedades.
|
||||
Comparar los atributos [`<td>` atributos](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td) con las propiedades [`<td>` propiedades](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) nos proporciona un ejemplo útil para poder diferenciar estos dos términos de una mejor manera.
|
||||
En particular, se puede navegar de la página de atributos a la página de propiedades por medio del enlace "Interfaz del DOM", y navegar la jerarquía de la herencia hasta `HTMLTableCellElement`.
|
||||
|
||||
|
||||
#### Example 1: an `<input>`
|
||||
#### Ejemplo 1: un `<input>`
|
||||
|
||||
When the browser renders `<input type="text" value="Sarah">`, it creates a
|
||||
corresponding DOM node with a `value` property initialized to "Sarah".
|
||||
Cuando el navegador renderiza `<input type="text" value="Sarah">`, este crea un nodo correspondiente en el DOM con la propiedad `value` inicializada con el valor de "Sarah".
|
||||
|
||||
```html
|
||||
<input type="text" value="Sarah">
|
||||
```
|
||||
|
||||
When the user enters "Sally" into the `<input>`, the DOM element `value` *property* becomes "Sally".
|
||||
However, if you look at the HTML attribute `value` using `input.getAttribute('value')`, you can see that the *attribute* remains unchanged—it returns "Sarah".
|
||||
Cuando el usuario ingresa "Sally" dentro del `<input>`, la **propiedad** `value` del elemento del DOM se convierte en "Sally".
|
||||
Sin embargo, si tu revisas el atributo HTML `value` usando el método `input.getAttribute('value')`, puedes notar que el *atributo* no ha cambiado—por lo que returna el valor de "Sarah".
|
||||
|
||||
The HTML attribute `value` specifies the *initial* value; the DOM `value` property is the *current* value.
|
||||
El atributo HTML `value` especifica el valor *inicial*; la propiedad del DOM `value` es el valor *actual*.
|
||||
|
||||
To see attributes versus DOM properties in a functioning app, see the <live-example name="binding-syntax"></live-example> especially for binding syntax.
|
||||
Para consultar los atributos vs las propiedades del DOM en una aplicación funcional, consulta la <live-example name="binding-syntax">aplicación</live-example> en especial para repasar la sintaxis de enlace.
|
||||
|
||||
#### Example 2: a disabled button
|
||||
#### Ejemplo 2: un botón desactivado
|
||||
|
||||
The `disabled` attribute is another example. A button's `disabled`
|
||||
*property* is `false` by default so the button is enabled.
|
||||
El atributo `disabled` es otro ejemplo. La *propiedad* del botón `disabled`
|
||||
*property* es `false` por defecto así que el botón esta activo.
|
||||
|
||||
When you add the `disabled` *attribute*, its presence alone
|
||||
initializes the button's `disabled` *property* to `true`
|
||||
so the button is disabled.
|
||||
Cuando añades el *atributo* `disabled`, su sola presencia inicializa la *propiedad* del botón `disabled` con el valor de `true` por lo que el botón esta desactivado.
|
||||
|
||||
```html
|
||||
<button disabled>Test Button</button>
|
||||
<button disabled>Botón de Ejemplo</button>
|
||||
```
|
||||
|
||||
Adding and removing the `disabled` *attribute* disables and enables the button.
|
||||
However, the value of the *attribute* is irrelevant,
|
||||
which is why you cannot enable a button by writing `<button disabled="false">Still Disabled</button>`.
|
||||
Añadir y eliminar el *atributo* `disabled` desactiva y activa el botón.
|
||||
Sin embargo, el valor del *atributo* es irrelevante,
|
||||
lo cual es la razón del por qué no puedes activar un botón escribiendo `<button disabled="false">Todavía Desactivado</button>`.
|
||||
|
||||
To control the state of the button, set the `disabled` *property*,
|
||||
Para controlar el estado de un botón, establece la *propiedad* `disabled`.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Though you could technically set the `[attr.disabled]` attribute binding, the values are different in that the property binding requires to a boolean value, while its corresponding attribute binding relies on whether the value is `null` or not. Consider the following:
|
||||
Aunque técnicamente podrías establecer el enlace de atributo `[attr.disabled]`, los valores son diferentes ya que el enlace de propiedad necesita un valor booleano, mientras que el enlace de atributo correspondiente depende de que su valor sea `null` o no. Por lo que considera lo siguiente:
|
||||
|
||||
```html
|
||||
<input [disabled]="condition ? true : false">
|
||||
<input [attr.disabled]="condition ? 'disabled' : null">
|
||||
```
|
||||
|
||||
Generally, use property binding over attribute binding as it is more intuitive (being a boolean value), has a shorter syntax, and is more performant.
|
||||
Por lo general usa enlace de propiedades sobre enlace de atributos ya que es más intuitivo (siendo un valor booleano), tienen una sintaxis corta y es más eficaz.
|
||||
|
||||
</div>
|
||||
|
||||
Para ver el ejemplo del botón `disabled`, consulta la <live-example name="binding-syntax">aplicación</live-example> en especial para revisar la sintaxis de enlace. Este ejemplo muestra como alternar la propiedad disabled desde el componente.
|
||||
|
||||
To see the `disabled` button example in a functioning app, see the <live-example name="binding-syntax"></live-example> especially for binding syntax. This example shows you how to toggle the disabled property from the component.
|
||||
## Tipos de enlace y objetivos
|
||||
|
||||
## Binding types and targets
|
||||
|
||||
The **target of a data-binding** is something in the DOM.
|
||||
Depending on the binding type, the target can be a property (element, component, or directive),
|
||||
an event (element, component, or directive), or sometimes an attribute name.
|
||||
The following table summarizes the targets for the different binding types.
|
||||
El **objetivo de un enlace de datos** se relaciona con algo del DOM.
|
||||
Dependiendo del tipo de enlace, el objetivo puede ser una propiedad (elemento, componente, o directiva),
|
||||
un evento (elemento, componente o directiva), o incluso algunas veces el nombre de un atributo.
|
||||
La siguiente tabla recoge los objetivos para los diferentes tipos de enlace.
|
||||
|
||||
<style>
|
||||
td, th {vertical-align: top}
|
||||
@ -229,23 +218,23 @@ The following table summarizes the targets for the different binding types.
|
||||
</col>
|
||||
<tr>
|
||||
<th>
|
||||
Type
|
||||
Tipo
|
||||
</th>
|
||||
<th>
|
||||
Target
|
||||
Objetivo
|
||||
</th>
|
||||
<th>
|
||||
Examples
|
||||
Ejemplos
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Property
|
||||
Propiedad
|
||||
</td>
|
||||
<td>
|
||||
Element property<br>
|
||||
Component property<br>
|
||||
Directive property
|
||||
Propiedad del elemento<br>
|
||||
Propiedad del componente<br>
|
||||
Propiedad de la directiva
|
||||
</td>
|
||||
<td>
|
||||
<code>src</code>, <code>hero</code>, and <code>ngClass</code> in the following:
|
||||
@ -255,12 +244,12 @@ The following table summarizes the targets for the different binding types.
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Event
|
||||
Evento
|
||||
</td>
|
||||
<td>
|
||||
Element event<br>
|
||||
Component event<br>
|
||||
Directive event
|
||||
Evento del elemento<br>
|
||||
Evento del componente<br>
|
||||
Evento de la directiva
|
||||
</td>
|
||||
<td>
|
||||
<code>click</code>, <code>deleteRequest</code>, and <code>myClick</code> in the following:
|
||||
@ -271,10 +260,10 @@ The following table summarizes the targets for the different binding types.
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Two-way
|
||||
Bidireccional
|
||||
</td>
|
||||
<td>
|
||||
Event and property
|
||||
Eventos y propiedades
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="2-way-binding-syntax-1"></code-example>
|
||||
@ -282,11 +271,11 @@ The following table summarizes the targets for the different binding types.
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Attribute
|
||||
Atributo
|
||||
</td>
|
||||
<td>
|
||||
Attribute
|
||||
(the exception)
|
||||
Atributo
|
||||
(la excepción)
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="attribute-binding-syntax-1"></code-example>
|
||||
@ -294,10 +283,10 @@ The following table summarizes the targets for the different binding types.
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Class
|
||||
Clase
|
||||
</td>
|
||||
<td>
|
||||
<code>class</code> property
|
||||
Propiedad de una <code>clase</code>
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="class-binding-syntax-1"></code-example>
|
||||
@ -305,14 +294,13 @@ The following table summarizes the targets for the different binding types.
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Style
|
||||
Estilos
|
||||
</td>
|
||||
<td>
|
||||
<code>style</code> property
|
||||
Propiedad de un <code>estilo</code>
|
||||
</td>
|
||||
<td>
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="style-binding-syntax-1"></code-example>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
174
aio/content/guide/bootstrapping.en.md
Normal file
174
aio/content/guide/bootstrapping.en.md
Normal file
@ -0,0 +1,174 @@
|
||||
# Launching your app with a root module
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
A basic understanding of the following:
|
||||
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).
|
||||
|
||||
<hr />
|
||||
|
||||
An NgModule describes how the application parts fit together.
|
||||
Every application has at least one Angular module, the _root_ module,
|
||||
which must be present for bootstrapping the application on launch.
|
||||
By convention and by default, this NgModule is named `AppModule`.
|
||||
|
||||
When you use the [Angular CLI](cli) command `ng new` to generate an app, the default `AppModule` is as follows.
|
||||
|
||||
```typescript
|
||||
/* JavaScript imports */
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpClientModule } from '@angular/common/http';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
/* the AppModule class with the @NgModule decorator */
|
||||
@NgModule({
|
||||
declarations: [
|
||||
AppComponent
|
||||
],
|
||||
imports: [
|
||||
BrowserModule,
|
||||
FormsModule,
|
||||
HttpClientModule
|
||||
],
|
||||
providers: [],
|
||||
bootstrap: [AppComponent]
|
||||
})
|
||||
export class AppModule { }
|
||||
|
||||
```
|
||||
|
||||
After the import statements is a class with the
|
||||
**`@NgModule`** [decorator](guide/glossary#decorator '"Decorator" explained').
|
||||
|
||||
The `@NgModule` decorator identifies `AppModule` as an `NgModule` class.
|
||||
`@NgModule` takes a metadata object that tells Angular how to compile and launch the application.
|
||||
|
||||
* **_declarations_**—this application's lone component.
|
||||
* **_imports_**—import `BrowserModule` to have browser specific services such as DOM rendering, sanitization, and location.
|
||||
* **_providers_**—the service providers.
|
||||
* **_bootstrap_**—the _root_ component that Angular creates and inserts
|
||||
into the `index.html` host web page.
|
||||
|
||||
The default application created by the Angular CLI only has one component, `AppComponent`, so it
|
||||
is in both the `declarations` and the `bootstrap` arrays.
|
||||
|
||||
{@a declarations}
|
||||
|
||||
## The `declarations` array
|
||||
|
||||
The module's `declarations` array tells Angular which components belong to that module.
|
||||
As you create more components, add them to `declarations`.
|
||||
|
||||
You must declare every component in exactly one `NgModule` class.
|
||||
If you use a component without declaring it, Angular returns an
|
||||
error message.
|
||||
|
||||
The `declarations` array only takes declarables. Declarables
|
||||
are components, [directives](guide/attribute-directives) and [pipes](guide/pipes).
|
||||
All of a module's declarables must be in the `declarations` array.
|
||||
Declarables must belong to exactly one module. The compiler emits
|
||||
an error if you try to declare the same class in more than one module.
|
||||
|
||||
These declared classes are visible within the module but invisible
|
||||
to components in a different module unless they are exported from
|
||||
this module and the other module imports this one.
|
||||
|
||||
An example of what goes into a declarations array follows:
|
||||
|
||||
```typescript
|
||||
declarations: [
|
||||
YourComponent,
|
||||
YourPipe,
|
||||
YourDirective
|
||||
],
|
||||
```
|
||||
|
||||
A declarable can only belong to one module, so only declare it in
|
||||
one `@NgModule`. When you need it elsewhere,
|
||||
import the module that has the declarable you need in it.
|
||||
|
||||
**Only `@NgModule` references** go in the `imports` array.
|
||||
|
||||
|
||||
### Using directives with `@NgModule`
|
||||
|
||||
Use the `declarations` array for directives.
|
||||
To use a directive, component, or pipe in a module, you must do a few things:
|
||||
|
||||
1. Export it from the file where you wrote it.
|
||||
2. Import it into the appropriate module.
|
||||
3. Declare it in the `@NgModule` `declarations` array.
|
||||
|
||||
|
||||
Those three steps look like the following. In the file where you create your directive, export it.
|
||||
The following example, named `ItemDirective` is the default directive structure that the CLI generates in its own file, `item.directive.ts`:
|
||||
|
||||
<code-example path="bootstrapping/src/app/item.directive.ts" region="directive" header="src/app/item.directive.ts"></code-example>
|
||||
|
||||
The key point here is that you have to export it so you can import it elsewhere. Next, import it
|
||||
into the `NgModule`, in this example `app.module.ts`, with a JavaScript import statement:
|
||||
|
||||
<code-example path="bootstrapping/src/app/app.module.ts" region="directive-import" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
And in the same file, add it to the `@NgModule` `declarations` array:
|
||||
|
||||
<code-example path="bootstrapping/src/app/app.module.ts" region="declarations" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
|
||||
Now you could use your `ItemDirective` in a component. This example uses `AppModule`, but you'd do it the same way for a feature module. For more about directives, see [Attribute Directives](guide/attribute-directives) and [Structural Directives](guide/structural-directives). You'd also use the same technique for [pipes](guide/pipes) and components.
|
||||
|
||||
Remember, components, directives, and pipes belong to one module only. You only need to declare them once in your app because you share them by importing the necessary modules. This saves you time and helps keep your app lean.
|
||||
|
||||
|
||||
|
||||
|
||||
{@a imports}
|
||||
|
||||
## The `imports` array
|
||||
|
||||
The module's `imports` array appears exclusively in the `@NgModule` metadata object.
|
||||
It tells Angular about other NgModules that this particular module needs to function properly.
|
||||
|
||||
This list of modules are those that export components, directives, or pipes
|
||||
that the component templates in this module reference. In this case, the component is
|
||||
`AppComponent`, which references components, directives, or pipes in `BrowserModule`,
|
||||
`FormsModule`, or `HttpClientModule`.
|
||||
A component template can reference another component, directive,
|
||||
or pipe when the referenced class is declared in this module or
|
||||
the class was imported from another module.
|
||||
|
||||
{@a bootstrap-array}
|
||||
|
||||
## The `providers` array
|
||||
|
||||
The providers array is where you list the services the app needs. When
|
||||
you list services here, they are available app-wide. You can scope
|
||||
them when using feature modules and lazy loading. For more information, see
|
||||
[Providers](guide/providers).
|
||||
|
||||
## The `bootstrap` array
|
||||
|
||||
The application launches by bootstrapping the root `AppModule`, which is
|
||||
also referred to as an `entryComponent`.
|
||||
Among other things, the bootstrapping process creates the component(s) listed in the `bootstrap` array
|
||||
and inserts each one into the browser DOM.
|
||||
|
||||
Each bootstrapped component is the base of its own tree of components.
|
||||
Inserting a bootstrapped component usually triggers a cascade of
|
||||
component creations that fill out that tree.
|
||||
|
||||
While you can put more than one component tree on a host web page,
|
||||
most applications have only one component tree and bootstrap a single root component.
|
||||
|
||||
This one root component is usually called `AppComponent` and is in the
|
||||
root module's `bootstrap` array.
|
||||
|
||||
|
||||
|
||||
## More about Angular Modules
|
||||
|
||||
For more on NgModules you're likely to see frequently in apps,
|
||||
see [Frequently Used Modules](guide/frequent-ngmodules).
|
@ -1,18 +1,18 @@
|
||||
# Launching your app with a root module
|
||||
# Lanzando tu aplicación con un módulo raíz
|
||||
|
||||
#### Prerequisites
|
||||
#### Pre-requisitos
|
||||
|
||||
A basic understanding of the following:
|
||||
Una comprensión básica de lo siguiente:
|
||||
* [JavaScript Modules vs. NgModules](guide/ngmodule-vs-jsmodule).
|
||||
|
||||
<hr />
|
||||
|
||||
An NgModule describes how the application parts fit together.
|
||||
Every application has at least one Angular module, the _root_ module,
|
||||
which must be present for bootstrapping the application on launch.
|
||||
By convention and by default, this NgModule is named `AppModule`.
|
||||
Un NgModule describe cómo encajan las partes de la aplicación.
|
||||
Cada aplicación tiene al menos un módulo Angular, el módulo _root_,
|
||||
que debe estar presente para arrancar la aplicación en el lanzamiento inicial.
|
||||
Por convención y por defecto, este NgModule se llama `AppModule`.
|
||||
|
||||
When you use the [Angular CLI](cli) command `ng new` to generate an app, the default `AppModule` is as follows.
|
||||
Cuando se usa el comando de [Angular CLI](cli) `ng new` para generar una aplicación, el `AppModule` predeterminado es el siguiente.
|
||||
|
||||
```typescript
|
||||
/* JavaScript imports */
|
||||
@ -40,43 +40,44 @@ export class AppModule { }
|
||||
|
||||
```
|
||||
|
||||
After the import statements is a class with the
|
||||
**`@NgModule`** [decorator](guide/glossary#decorator '"Decorator" explained').
|
||||
Después de las declaraciones de importación hay una clase con
|
||||
[decorador](guide/glossary#decorator 'Explicando "Decorator"') **`@NgModule`**.
|
||||
|
||||
The `@NgModule` decorator identifies `AppModule` as an `NgModule` class.
|
||||
`@NgModule` takes a metadata object that tells Angular how to compile and launch the application.
|
||||
El decorador `@NgModule` identifica `AppModule` como una clase `NgModule`.
|
||||
`@NgModule` toma un objeto de metadatos que le dice a Angular cómo compilar e iniciar la aplicación.
|
||||
|
||||
* **_declarations_**—this application's lone component.
|
||||
* **_imports_**—import `BrowserModule` to have browser specific services such as DOM rendering, sanitization, and location.
|
||||
* **_providers_**—the service providers.
|
||||
* **_bootstrap_**—the _root_ component that Angular creates and inserts
|
||||
into the `index.html` host web page.
|
||||
* **_declarations_**— el único componente de esta aplicación..
|
||||
* **_imports_**— importar `BrowserModule` para tener servicios específicos del navegador como renderizado DOM, sanitization y ubicación.
|
||||
* **_providers_**— los proveedores de servicios.
|
||||
* **_bootstrap_**— el componente raíz que Angular crea e inserta
|
||||
en la página web de host `index.html`.
|
||||
|
||||
The default application created by the Angular CLI only has one component, `AppComponent`, so it
|
||||
is in both the `declarations` and the `bootstrap` arrays.
|
||||
La aplicación predeterminada creada por Angular CLI solo tiene un componente, `AppComponent`, por lo que
|
||||
está en los arrays de `declarations` y `bootstrap`.
|
||||
|
||||
{@a the-declarations-array}
|
||||
{@a declarations}
|
||||
|
||||
## The `declarations` array
|
||||
## El array `declarations`
|
||||
|
||||
The module's `declarations` array tells Angular which components belong to that module.
|
||||
As you create more components, add them to `declarations`.
|
||||
El array de `declarations` le dice a Angular qué componentes pertenecen a ese módulo.
|
||||
A medida que crees más componentes, agrégalos a las `declarations`.
|
||||
|
||||
You must declare every component in exactly one `NgModule` class.
|
||||
If you use a component without declaring it, Angular returns an
|
||||
error message.
|
||||
Debe declarar cada componente en exactamente una clase `NgModule`.
|
||||
Si se usa un componente sin declararlo, Angular devuelve un
|
||||
mensaje de error.
|
||||
|
||||
The `declarations` array only takes declarables. Declarables
|
||||
are components, [directives](guide/attribute-directives) and [pipes](guide/pipes).
|
||||
All of a module's declarables must be in the `declarations` array.
|
||||
Declarables must belong to exactly one module. The compiler emits
|
||||
an error if you try to declare the same class in more than one module.
|
||||
El array `declarations` solo acepta declarables. Declarables pueden ser
|
||||
componentes, [directivas](guide/attribute-directives) y [pipes](guide/pipes).
|
||||
Todos los declarables de un módulo deben estar en el array de `declarations`.
|
||||
Los declarables deben pertenecer exactamente a un módulo. El compilador emite
|
||||
un error si se intenta declarar la misma clase en más de un módulo.
|
||||
|
||||
These declared classes are visible within the module but invisible
|
||||
to components in a different module unless they are exported from
|
||||
this module and the other module imports this one.
|
||||
Estas clases declaradas son visibles dentro del módulo pero invisibles
|
||||
a componentes en un módulo diferente, a menos que se exporten desde
|
||||
éste módulo y el otro módulo importe éste mismo módulo.
|
||||
|
||||
An example of what goes into a declarations array follows:
|
||||
A continuación, se muestra un ejemplo de un array `declarations`:
|
||||
|
||||
```typescript
|
||||
declarations: [
|
||||
@ -86,89 +87,86 @@ An example of what goes into a declarations array follows:
|
||||
],
|
||||
```
|
||||
|
||||
A declarable can only belong to one module, so only declare it in
|
||||
one `@NgModule`. When you need it elsewhere,
|
||||
import the module that has the declarable you need in it.
|
||||
Un declarable solo puede pertenecer a un módulo, por lo que solo debe ser declarado en
|
||||
un `@NgModule`. Cuando se necesite en otro lugar,
|
||||
importa el módulo que tiene el declarable que necesites.
|
||||
|
||||
**Only `@NgModule` references** go in the `imports` array.
|
||||
**Solo las referencias de `@NgModule`** van en el array `imports`.
|
||||
|
||||
|
||||
### Using directives with `@NgModule`
|
||||
### Usando directivas con `@NgModule`
|
||||
|
||||
Use the `declarations` array for directives.
|
||||
To use a directive, component, or pipe in a module, you must do a few things:
|
||||
Usa el array `declarations` para las directivas.
|
||||
Para usar una directiva, un componente o un pipe en un módulo, hay que hacer algunas cosas:
|
||||
|
||||
1. Export it from the file where you wrote it.
|
||||
2. Import it into the appropriate module.
|
||||
3. Declare it in the `@NgModule` `declarations` array.
|
||||
1. Exportarlo desde el archivo donde se escribió.
|
||||
2. Importarlo al módulo apropiado.
|
||||
3. Declararlo en el array `declarations` del `@NgModule`.
|
||||
|
||||
|
||||
Those three steps look like the following. In the file where you create your directive, export it.
|
||||
The following example, named `ItemDirective` is the default directive structure that the CLI generates in its own file, `item.directive.ts`:
|
||||
Esos tres pasos se parecen a los siguientes. En el archivo donde se crea la directiva, expórtalo.
|
||||
El siguiente ejemplo, llamado `ItemDirective` es la estructura de directiva predeterminada que la CLI genera en su propio archivo, `item.directive.ts`:
|
||||
|
||||
<code-example path="bootstrapping/src/app/item.directive.ts" region="directive" header="src/app/item.directive.ts"></code-example>
|
||||
|
||||
The key point here is that you have to export it so you can import it elsewhere. Next, import it
|
||||
into the `NgModule`, in this example `app.module.ts`, with a JavaScript import statement:
|
||||
El punto clave aquí es que se debe exportar para poder importarlo en otro lugar. A continuación, importar
|
||||
en el `NgModule`, en este ejemplo, `app.module.ts` con una declaración de importación de JavaScript:
|
||||
|
||||
<code-example path="bootstrapping/src/app/app.module.ts" region="directive-import" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
And in the same file, add it to the `@NgModule` `declarations` array:
|
||||
Y en el mismo archivo, agregarlo al array `declarations` del `@ NgModule`:
|
||||
|
||||
<code-example path="bootstrapping/src/app/app.module.ts" region="declarations" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
|
||||
Now you could use your `ItemDirective` in a component. This example uses `AppModule`, but you'd do it the same way for a feature module. For more about directives, see [Attribute Directives](guide/attribute-directives) and [Structural Directives](guide/structural-directives). You'd also use the same technique for [pipes](guide/pipes) and components.
|
||||
|
||||
Remember, components, directives, and pipes belong to one module only. You only need to declare them once in your app because you share them by importing the necessary modules. This saves you time and helps keep your app lean.
|
||||
|
||||
Ahora puedes usar tu `ItemDirective` en un componente. Este ejemplo usa `AppModule`, pero se haría de la misma manera para un módulo de funciones. Para obtener más información sobre las directivas, consulta [Directivas de atributos](guide/attribute-directives) y [Directivas estructurales](guide/structural-directives). También se usaría la misma técnica para [pipes](guide/pipes) y componentes.
|
||||
|
||||
Recuerda, los componentes, directivas y pipes pertenecen a un solo módulo. Solo se necesita declararlos una vez en tu aplicación porque se comparten importando los módulos necesarios. Esto ahorra tiempo y ayuda a mantener la aplicación optimizada.
|
||||
|
||||
|
||||
{@a imports}
|
||||
|
||||
## The `imports` array
|
||||
## El array de `imports`
|
||||
|
||||
The module's `imports` array appears exclusively in the `@NgModule` metadata object.
|
||||
It tells Angular about other NgModules that this particular module needs to function properly.
|
||||
El array de `imports` del módulo aparece exclusivamente en el objeto de metadatos del `@NgModule`.
|
||||
Le dice a Angular sobre otros NgModules que este módulo en particular necesita para funcionar correctamente.
|
||||
|
||||
This list of modules are those that export components, directives, or pipes
|
||||
that the component templates in this module reference. In this case, the component is
|
||||
`AppComponent`, which references components, directives, or pipes in `BrowserModule`,
|
||||
`FormsModule`, or `HttpClientModule`.
|
||||
A component template can reference another component, directive,
|
||||
or pipe when the referenced class is declared in this module or
|
||||
the class was imported from another module.
|
||||
Esta lista de módulos son los que exportan componentes, directivas o pipes
|
||||
que las plantillas de componentes en este módulo hacen referencia. En este caso, el componente es
|
||||
`AppComponent`, que hace referencia a componentes, directivas o pipes en `BrowserModule`,
|
||||
`FormsModule`, o `HttpClientModule`.
|
||||
Una plantilla de componente puede hacer referencia a otro componente, directiva,
|
||||
o pipe cuando la clase referenciada se declara en este módulo o
|
||||
la clase se importó de otro módulo.
|
||||
|
||||
{@a bootstrap-array}
|
||||
|
||||
## The `providers` array
|
||||
## El array `providers`
|
||||
|
||||
The providers array is where you list the services the app needs. When
|
||||
you list services here, they are available app-wide. You can scope
|
||||
them when using feature modules and lazy loading. For more information, see
|
||||
[Providers](guide/providers).
|
||||
El array `providers` es donde se enumeran los servicios que necesita la aplicación. Cuando
|
||||
enumera los servicios, están disponibles en toda la aplicación. Puedes reducir el scope
|
||||
al usar módulos de funciones y carga diferida. Para más información, ver
|
||||
[Proveedores](guide/providers).
|
||||
|
||||
## The `bootstrap` array
|
||||
## El array `bootstrap`
|
||||
|
||||
The application launches by bootstrapping the root `AppModule`, which is
|
||||
also referred to as an `entryComponent`.
|
||||
Among other things, the bootstrapping process creates the component(s) listed in the `bootstrap` array
|
||||
and inserts each one into the browser DOM.
|
||||
La aplicación se inicia haciendo bootstraping desde la raíz `AppModule`, que es
|
||||
también conocido como `entryComponent`.
|
||||
Entre otras cosas, el proceso de carga crea los componentes enumerados en el array de `bootstrap`
|
||||
e inserta cada uno en el DOM del navegador.
|
||||
|
||||
Each bootstrapped component is the base of its own tree of components.
|
||||
Inserting a bootstrapped component usually triggers a cascade of
|
||||
component creations that fill out that tree.
|
||||
Cada componente bootstrap es la base de su propio árbol de componentes.
|
||||
La inserción de un componente bootstrapped generalmente desencadena una cascada de
|
||||
creaciones de componentes que completan ese árbol.
|
||||
|
||||
While you can put more than one component tree on a host web page,
|
||||
most applications have only one component tree and bootstrap a single root component.
|
||||
Si bien puedes colocar más de un árbol de componentes en una página web de host,
|
||||
la mayoría de las aplicaciones tienen solo un árbol de componentes y arrancan un solo componente raíz.
|
||||
|
||||
This one root component is usually called `AppComponent` and is in the
|
||||
root module's `bootstrap` array.
|
||||
Este componente raíz se suele llamar `AppComponent` y se encuentra en el
|
||||
array `bootstrap` del módulo raíz.
|
||||
|
||||
|
||||
## Más sobre módulos Angular
|
||||
|
||||
## More about Angular Modules
|
||||
|
||||
For more on NgModules you're likely to see frequently in apps,
|
||||
see [Frequently Used Modules](guide/frequent-ngmodules).
|
||||
Para obtener más información sobre NgModules que probablemente veas con frecuencia en las aplicaciones,
|
||||
consulta [Módulos de uso frecuente](guide/frequent-ngmodules).
|
||||
|
104
aio/content/guide/complex-animation-sequences.en.md
Normal file
104
aio/content/guide/complex-animation-sequences.en.md
Normal file
@ -0,0 +1,104 @@
|
||||
# Complex animation sequences
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
A basic understanding of the following concepts:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
|
||||
<hr>
|
||||
|
||||
So far, we've learned simple animations of single HTML elements. Angular also lets you animate coordinated sequences, such as an entire grid or list of elements as they enter and leave a page. You can choose to run multiple animations in parallel, or run discrete animations sequentially, one following another.
|
||||
|
||||
Functions that control complex animation sequences are as follows:
|
||||
|
||||
* `query()` finds one or more inner HTML elements.
|
||||
* `stagger()` applies a cascading delay to animations for multiple elements.
|
||||
* [`group()`](api/animations/group) runs multiple animation steps in parallel.
|
||||
* `sequence()` runs animation steps one after another.
|
||||
|
||||
{@a complex-sequence}
|
||||
|
||||
## Animate multiple elements using query() and stagger() functions
|
||||
|
||||
The `query()` function allows you to find inner elements within the element that is being animated. This function targets specific HTML elements within a parent component and applies animations to each element individually. Angular intelligently handles setup, teardown, and cleanup as it coordinates the elements across the page.
|
||||
|
||||
The `stagger()` function allows you to define a timing gap between each queried item that is animated and thus animates elements with a delay between them.
|
||||
|
||||
The Filter/Stagger tab in the live example shows a list of heroes with an introductory sequence. The entire list of heroes cascades in, with a slight delay from top to bottom.
|
||||
|
||||
The following example demonstrates how to use `query()` and `stagger()` functions on the entry of an animated element.
|
||||
|
||||
* Use `query()` to look for an element entering the page that meets certain criteria.
|
||||
|
||||
* For each of these elements, use `style()` to set the same initial style for the element. Make it invisible and use `transform` to move it out of position so that it can slide into place.
|
||||
|
||||
* Use `stagger()` to delay each animation by 30 milliseconds.
|
||||
|
||||
* Animate each element on screen for 0.5 seconds using a custom-defined easing curve, simultaneously fading it in and un-transforming it.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-page.component.ts" header="src/app/hero-list-page.component.ts" region="page-animations" language="typescript"></code-example>
|
||||
|
||||
## Parallel animation using group() function
|
||||
|
||||
You've seen how to add a delay between each successive animation. But you may also want to configure animations that happen in parallel. For example, you may want to animate two CSS properties of the same element but use a different `easing` function for each one. For this, you can use the animation [`group()`](api/animations/group) function.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The [`group()`](api/animations/group) function is used to group animation *steps*, rather than animated elements.
|
||||
</div>
|
||||
|
||||
In the following example, using groups on both `:enter` and `:leave` allow for two different timing configurations. They're applied to the same element in parallel, but run independently.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-groups.component.ts" region="animationdef" header="src/app/hero-list-groups.component.ts (excerpt)" language="typescript"></code-example>
|
||||
|
||||
## Sequential vs. parallel animations
|
||||
|
||||
Complex animations can have many things happening at once. But what if you want to create an animation involving several animations happening one after the other? Earlier we used [`group()`](api/animations/group) to run multiple animations all at the same time, in parallel.
|
||||
|
||||
A second function called `sequence()` lets you run those same animations one after the other. Within `sequence()`, the animation steps consist of either `style()` or `animate()` function calls.
|
||||
|
||||
* Use `style()` to apply the provided styling data immediately.
|
||||
* Use `animate()` to apply styling data over a given time interval.
|
||||
|
||||
## Filter animation example
|
||||
|
||||
Let's take a look at another animation on the live example page. Under the Filter/Stagger tab, enter some text into the **Search Heroes** text box, such as `Magnet` or `tornado`.
|
||||
|
||||
The filter works in real time as you type. Elements leave the page as you type each new letter and the filter gets progressively stricter. The heroes list gradually re-enters the page as you delete each letter in the filter box.
|
||||
|
||||
The HTML template contains a trigger called `filterAnimation`.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-page.component.html" header="src/app/hero-list-page.component.html" region="filter-animations"></code-example>
|
||||
|
||||
The component file contains three transitions.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-page.component.ts" header="src/app/hero-list-page.component.ts" region="filter-animations" language="typescript"></code-example>
|
||||
|
||||
The animation does the following:
|
||||
|
||||
* Ignores any animations that are performed when the user first opens or navigates to this page. The filter narrows what is already there, so it assumes that any HTML elements to be animated already exist in the DOM.
|
||||
|
||||
* Performs a filter match for matches.
|
||||
|
||||
For each match:
|
||||
|
||||
* Hides the element by making it completely transparent and infinitely narrow, by setting its opacity and width to 0.
|
||||
|
||||
* Animates in the element over 300 milliseconds. During the animation, the element assumes its default width and opacity.
|
||||
|
||||
* If there are multiple matching elements, staggers in each element starting at the top of the page, with a 50-millisecond delay between each element.
|
||||
|
||||
## Animation sequence summary
|
||||
|
||||
Angular functions for animating multiple elements start with `query()` to find inner elements, for example gathering all images within a `<div>`. The remaining functions, `stagger()`, [`group()`](api/animations/group), and `sequence()`, apply cascades or allow you to control how multiple animation steps are applied.
|
||||
|
||||
## More on Angular animations
|
||||
|
||||
You may also be interested in the following:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
* [Reusable animations](guide/reusable-animations)
|
||||
* [Route transition animations](guide/route-animations)
|
@ -1,104 +1,105 @@
|
||||
# Complex animation sequences
|
||||
# Secuencias de animación complejas
|
||||
|
||||
#### Prerequisites
|
||||
#### Requisitos
|
||||
|
||||
A basic understanding of the following concepts:
|
||||
Una comprensión básica de los siguientes conceptos:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
- [Introducción a animaciones Angular](guide/animations)
|
||||
- [Transición y triggers](guide/transition-and-triggers)
|
||||
|
||||
<hr>
|
||||
|
||||
So far, we've learned simple animations of single HTML elements. Angular also lets you animate coordinated sequences, such as an entire grid or list of elements as they enter and leave a page. You can choose to run multiple animations in parallel, or run discrete animations sequentially, one following another.
|
||||
Hasta ahora, hemos aprendido animaciones simples de elementos HTML individuales. Angular también te permite animar secuencias coordinadas, como un grid completo o una lista de elementos cuando entran y salen de una página. Puedes elegir ejecutar varias animaciones en paralelo, o ejecutar animaciones discretas secuencialmente, una tras otra.
|
||||
|
||||
Functions that control complex animation sequences are as follows:
|
||||
Las funciones que controlan secuencias de animación complejas son las siguientes:
|
||||
|
||||
* `query()` finds one or more inner HTML elements.
|
||||
* `stagger()` applies a cascading delay to animations for multiple elements.
|
||||
* [`group()`](api/animations/group) runs multiple animation steps in parallel.
|
||||
* `sequence()` runs animation steps one after another.
|
||||
- `query()` encuentra uno o más elementos HTML internos.
|
||||
- `stagger()` aplica un retraso en cascada a las animaciones para varios elementos.
|
||||
- [`group()`](api/animations/group) ejecuta varios pasos de animación en paralelo.
|
||||
- `sequence()` ejecuta pasos de animación uno tras otro.
|
||||
|
||||
{@a complex-sequence}
|
||||
|
||||
## Animate multiple elements using query() and stagger() functions
|
||||
## Animar varios elementos usando las funciones query() y stagger()
|
||||
|
||||
The `query()` function allows you to find inner elements within the element that is being animated. This function targets specific HTML elements within a parent component and applies animations to each element individually. Angular intelligently handles setup, teardown, and cleanup as it coordinates the elements across the page.
|
||||
La función `query()` permite encontrar elementos internos dentro del elemento que estás animando. Esta función se dirige a elementos HTML específicos dentro de un componente principal y aplica animaciones a cada elemento individualmente. Angular maneja de manera inteligente la configuración, el desmontaje y la limpieza a medida que coordina los elementos en la página.
|
||||
|
||||
The `stagger()` function allows you to define a timing gap between each queried item that is animated and thus animates elements with a delay between them.
|
||||
La función `stagger()` permite definir un intervalo de tiempo entre cada elemento consultado que está animado y, por lo tanto, anima elementos con un retraso entre ellos.
|
||||
|
||||
The Filter/Stagger tab in the live example shows a list of heroes with an introductory sequence. The entire list of heroes cascades in, with a slight delay from top to bottom.
|
||||
La pestaña Filter/Stagger en el ejemplo en vivo muestra una lista de héroes con una secuencia introductoria. La lista completa de héroes entra en cascada, con un ligero retraso de arriba a abajo.
|
||||
|
||||
The following example demonstrates how to use `query()` and `stagger()` functions on the entry of an animated element.
|
||||
El siguiente ejemplo demuestra cómo utilizar las funciones `query()` y `stagger()` en la entrada de un elemento animado.
|
||||
|
||||
* Use `query()` to look for an element entering the page that meets certain criteria.
|
||||
- Usa `query()` para buscar un elemento que ingrese a la página que cumpla con ciertos criterios.
|
||||
|
||||
* For each of these elements, use `style()` to set the same initial style for the element. Make it invisible and use `transform` to move it out of position so that it can slide into place.
|
||||
- Para cada uno de estos elementos, usa `style()` para establecer el mismo estilo inicial para el elemento. Hazlo invisible y usa `transform` para moverlo fuera de su posición para que pueda deslizarse a su lugar.
|
||||
|
||||
* Use `stagger()` to delay each animation by 30 milliseconds.
|
||||
- Usa `stagger()` para retrasar cada animación en 30 milisegundos.
|
||||
|
||||
* Animate each element on screen for 0.5 seconds using a custom-defined easing curve, simultaneously fading it in and un-transforming it.
|
||||
- Anima cada elemento en la pantalla durante 0,5 segundos utilizando una curva de easing (suavizado) definida a medida, desvaneciéndolo y deshaciéndolo simultáneamente.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-page.component.ts" header="src/app/hero-list-page.component.ts" region="page-animations" language="typescript"></code-example>
|
||||
|
||||
## Parallel animation using group() function
|
||||
## Animación paralela usando la función group()
|
||||
|
||||
You've seen how to add a delay between each successive animation. But you may also want to configure animations that happen in parallel. For example, you may want to animate two CSS properties of the same element but use a different `easing` function for each one. For this, you can use the animation [`group()`](api/animations/group) function.
|
||||
Has visto cómo agregar un retraso entre cada animación sucesiva. Pero es posible que también quieras configurar animaciones que suceden en paralelo. Por ejemplo, es posible que quieras animar dos propiedades CSS del mismo elemento pero utilizar una función de `easing` diferente para cada una. Para ello, puedes utilizar la función de animación [`group()`](api/animations/group).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The [`group()`](api/animations/group) function is used to group animation *steps*, rather than animated elements.
|
||||
**Nota:** La función [`group()`](api/animations/group) se usa para agrupar _pasos_ de animación, en lugar de elementos animados.
|
||||
|
||||
</div>
|
||||
|
||||
In the following example, using groups on both `:enter` and `:leave` allow for two different timing configurations. They're applied to the same element in parallel, but run independently.
|
||||
En el siguiente ejemplo, el uso de grupos tanto en `:enter` como en `:leave` permite dos configuraciones de tiempo diferentes. Se aplican al mismo elemento en paralelo, pero se ejecutan de forma independiente.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-groups.component.ts" region="animationdef" header="src/app/hero-list-groups.component.ts (excerpt)" language="typescript"></code-example>
|
||||
|
||||
## Sequential vs. parallel animations
|
||||
## Animaciones secuenciales vs paralelas
|
||||
|
||||
Complex animations can have many things happening at once. But what if you want to create an animation involving several animations happening one after the other? Earlier we used [`group()`](api/animations/group) to run multiple animations all at the same time, in parallel.
|
||||
Las animaciones complejas pueden tener muchas cosas sucediendo a la vez. Pero, ¿qué sucede si quieres crear una animación que involucre varias animaciones sucediendo una tras otra? Anteriormente usamos [`group()`](api/animations/group) para ejecutar múltiples animaciones al mismo tiempo, en paralelo.
|
||||
|
||||
A second function called `sequence()` lets you run those same animations one after the other. Within `sequence()`, the animation steps consist of either `style()` or `animate()` function calls.
|
||||
Una segunda función llamada `sequence()` permite ejecutar esas mismas animaciones una tras otra. Dentro de `sequence()`, los pasos de la animación consisten en llamadas de función `style()` o `animate()`
|
||||
|
||||
* Use `style()` to apply the provided styling data immediately.
|
||||
* Use `animate()` to apply styling data over a given time interval.
|
||||
- Usa `style()` para aplicar los datos de estilo proporcionados inmediatamente.
|
||||
- Usa `animate()` para aplicar datos de estilo en un intervalo de tiempo determinado.
|
||||
|
||||
## Filter animation example
|
||||
## Ejemplo de animación de filtro
|
||||
|
||||
Let's take a look at another animation on the live example page. Under the Filter/Stagger tab, enter some text into the **Search Heroes** text box, such as `Magnet` or `tornado`.
|
||||
Echemos un vistazo a otra animación en la página de ejemplo. En la pestaña Filter/Stagger, ingresa un texto en el cuadro de texto **Search Heroes**, como `Magnet` o `tornado`.
|
||||
|
||||
The filter works in real time as you type. Elements leave the page as you type each new letter and the filter gets progressively stricter. The heroes list gradually re-enters the page as you delete each letter in the filter box.
|
||||
El filtro funciona en tiempo real a medida que escribe. Los elementos abandonan la página a medida que escribe cada nueva letra y el filtro se vuelve progresivamente más estricto. La lista de héroes vuelve a entrar gradualmente en la página a medida que eliminas cada letra en la caja de filtro.
|
||||
|
||||
The HTML template contains a trigger called `filterAnimation`.
|
||||
La plantilla HTML contiene un trigger llamado `filterAnimation`.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-page.component.html" header="src/app/hero-list-page.component.html" region="filter-animations"></code-example>
|
||||
|
||||
The component file contains three transitions.
|
||||
El archivo del componente contiene tres transiciones.
|
||||
|
||||
<code-example path="animations/src/app/hero-list-page.component.ts" header="src/app/hero-list-page.component.ts" region="filter-animations" language="typescript"></code-example>
|
||||
|
||||
The animation does the following:
|
||||
La animación hace lo siguiente:
|
||||
|
||||
* Ignores any animations that are performed when the user first opens or navigates to this page. The filter narrows what is already there, so it assumes that any HTML elements to be animated already exist in the DOM.
|
||||
- Ignora las animaciones que se realizan cuando el usuario abre o navega por primera vez a esta página. El filtro reduce lo que ya está allí, por lo que asume que los elementos HTML que se van a animar ya existen en el DOM.
|
||||
|
||||
* Performs a filter match for matches.
|
||||
- Realiza un filtro de coincidencia.
|
||||
|
||||
For each match:
|
||||
Para cada coincidencia:
|
||||
|
||||
* Hides the element by making it completely transparent and infinitely narrow, by setting its opacity and width to 0.
|
||||
- Oculta el elemento haciéndolo completamente transparente e infinitamente estrecho, estableciendo su opacidad y ancho en 0.
|
||||
|
||||
* Animates in the element over 300 milliseconds. During the animation, the element assumes its default width and opacity.
|
||||
- Anima el elemento más de 300 milisegundos. Durante la animación, el elemento asume su ancho y opacidad predeterminados.
|
||||
|
||||
* If there are multiple matching elements, staggers in each element starting at the top of the page, with a 50-millisecond delay between each element.
|
||||
- Si hay varios elementos coincidentes, se escalona en cada elemento comenzando en la parte superior de la página, con un retraso de 50 milisegundos entre cada elemento.
|
||||
|
||||
## Animation sequence summary
|
||||
## Resumen de la secuencia de animación
|
||||
|
||||
Angular functions for animating multiple elements start with `query()` to find inner elements, for example gathering all images within a `<div>`. The remaining functions, `stagger()`, [`group()`](api/animations/group), and `sequence()`, apply cascades or allow you to control how multiple animation steps are applied.
|
||||
Las funciones Angular para animar múltiples elementos comienzan con `query()` para encontrar elementos internos, por ejemplo, reuniendo todas las imágenes dentro de un `<div>`. Las funciones restantes, `stagger()`, [`group()`](api/animations/group) y `sequence()`, aplican cascadas o te permiten controlar cómo se aplican múltiples pasos de animación.
|
||||
|
||||
## More on Angular animations
|
||||
## Más sobre animaciones en Angular
|
||||
|
||||
You may also be interested in the following:
|
||||
También puedes estar interesado en lo siguiente:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
* [Reusable animations](guide/reusable-animations)
|
||||
* [Route transition animations](guide/route-animations)
|
||||
- [Introducción a animaciones Angular](guide/animations)
|
||||
- [Transición y triggers](guide/transition-and-triggers)
|
||||
- [Animaicones reusables](guide/reusable-animations)
|
||||
- [Animaciones en transición de ruta](guide/route-animations)
|
||||
|
245
aio/content/guide/creating-libraries.en.md
Normal file
245
aio/content/guide/creating-libraries.en.md
Normal file
@ -0,0 +1,245 @@
|
||||
# Creating libraries
|
||||
|
||||
This page provides a conceptual overview of how you can create and publish new libraries to extend Angular functionality.
|
||||
|
||||
If you find that you need to solve the same problem in more than one app (or want to share your solution with other developers), you have a candidate for a library.
|
||||
A simple example might be a button that sends users to your company website, that would be included in all apps that your company builds.
|
||||
|
||||
## Getting started
|
||||
|
||||
Use the Angular CLI to generate a new library skeleton in a new workspace with the following commands.
|
||||
|
||||
<code-example language="bash">
|
||||
ng new my-workspace --create-application=false
|
||||
cd my-workspace
|
||||
ng generate library my-lib
|
||||
</code-example>
|
||||
|
||||
The `ng generate` command creates the `projects/my-lib` folder in your workspace, which contains a component and a service inside an NgModule.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For more details on how a library project is structured, refer to the [Library project files](guide/file-structure#library-project-files) section of the [Project File Structure guide](guide/file-structure).
|
||||
|
||||
You can use the monorepo model to use the same workspace for multiple projects.
|
||||
See [Setting up for a multi-project workspace](guide/file-structure#multiple-projects).
|
||||
|
||||
</div>
|
||||
|
||||
When you generate a new library, the workspace configuration file, `angular.json`, is updated with a project of type 'library'.
|
||||
|
||||
<code-example format="json">
|
||||
"projects": {
|
||||
...
|
||||
"my-lib": {
|
||||
"root": "projects/my-lib",
|
||||
"sourceRoot": "projects/my-lib/src",
|
||||
"projectType": "library",
|
||||
"prefix": "lib",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular-devkit/build-ng-packagr:build",
|
||||
...
|
||||
</code-example>
|
||||
|
||||
You can build, test, and lint the project with CLI commands:
|
||||
|
||||
<code-example language="bash">
|
||||
ng build my-lib
|
||||
ng test my-lib
|
||||
ng lint my-lib
|
||||
</code-example>
|
||||
|
||||
Notice that the configured builder for the project is different from the default builder for app projects.
|
||||
This builder, among other things, ensures that the library is always built with the [AOT compiler](guide/aot-compiler), without the need to specify the `--prod` flag.
|
||||
|
||||
To make library code reusable you must define a public API for it. This "user layer" defines what is available to consumers of your library. A user of your library should be able to access public functionality (such as NgModules, service providers and general utility functions) through a single import path.
|
||||
|
||||
The public API for your library is maintained in the `public-api.ts` file in your library folder.
|
||||
Anything exported from this file is made public when your library is imported into an application.
|
||||
Use an NgModule to expose services and components.
|
||||
|
||||
Your library should supply documentation (typically a README file) for installation and maintenance.
|
||||
|
||||
## Refactoring parts of an app into a library
|
||||
|
||||
To make your solution reusable, you need to adjust it so that it does not depend on app-specific code.
|
||||
Here are some things to consider in migrating application functionality to a library.
|
||||
|
||||
* Declarations such as components and pipes should be designed as stateless, meaning they don’t rely on or alter external variables. If you do rely on state, you need to evaluate every case and decide whether it is application state or state that the library would manage.
|
||||
|
||||
* Any observables that the components subscribe to internally should be cleaned up and disposed of during the lifecycle of those components.
|
||||
|
||||
* Components should expose their interactions through inputs for providing context, and outputs for communicating events to other components.
|
||||
|
||||
* Check all internal dependencies.
|
||||
* For custom classes or interfaces used in components or service, check whether they depend on additional classes or interfaces that also need to be migrated.
|
||||
* Similarly, if your library code depends on a service, that service needs to be migrated.
|
||||
* If your library code or its templates depend on other libraries (such as Angular Material, for instance), you must configure your library with those dependencies.
|
||||
|
||||
* Consider how you provide services to client applications.
|
||||
|
||||
* Services should declare their own providers (rather than declaring providers in the NgModule or a component), so that they are *tree-shakable*. This allows the compiler to leave the service out of the bundle if it never gets injected into the application that imports the library. For more about this, see [Tree-shakable providers](guide/dependency-injection-providers#tree-shakable-providers).
|
||||
|
||||
* If you register global service providers or share providers across multiple NgModules, use the [`forRoot()` and `forChild()` design patterns](guide/singleton-services) provided by the [RouterModule](api/router/RouterModule).
|
||||
|
||||
* If your library provides optional services that might not be used by all client applications, support proper tree-shaking for that case by using the [lightweight token design pattern](guide/lightweight-injection-tokens).
|
||||
|
||||
{@a integrating-with-the-cli}
|
||||
|
||||
## Integrating with the CLI using code-generation schematics
|
||||
|
||||
A library typically includes *reusable code* that defines components, services, and other Angular artifacts (pipes, directives, and so on) that you simply import into a project.
|
||||
A library is packaged into an npm package for publishing and sharing.
|
||||
This package can also include [schematics](guide/glossary#schematic) that provide instructions for generating or transforming code directly in your project, in the same way that the CLI creates a generic new component with `ng generate component`.
|
||||
A schematic that is packaged with a library can, for example, provide the Angular CLI with the information it needs to generate a component that configures and uses a particular feature, or set of features, defined in that library.
|
||||
One example of this is Angular Material's navigation schematic which configures the CDK's `BreakpointObserver` and uses it with Material's `MatSideNav` and `MatToolbar` components.
|
||||
|
||||
You can create and include the following kinds of schematics.
|
||||
|
||||
* Include an installation schematic so that `ng add` can add your library to a project.
|
||||
|
||||
* Include generation schematics in your library so that `ng generate` can scaffold your defined artifacts (components, services, tests, and so on) in a project.
|
||||
|
||||
* Include an update schematic so that `ng update` can update your library’s dependencies and provide migrations for breaking changes in new releases.
|
||||
|
||||
What you include in your library depends on your task.
|
||||
For example, you could define a schematic to create a dropdown that is pre-populated with canned data to show how to add it to an app.
|
||||
If you want a dropdown that would contain different passed-in values each time, your library could define a schematic to create it with a given configuration. Developers could then use `ng generate` to configure an instance for their own app.
|
||||
|
||||
Suppose you want to read a configuration file and then generate a form based on that configuration.
|
||||
If that form will need additional customization by the developer who is using your library, it might work best as a schematic.
|
||||
However, if the forms will always be the same and not need much customization by developers, then you could create a dynamic component that takes the configuration and generates the form.
|
||||
In general, the more complex the customization, the more useful the schematic approach.
|
||||
|
||||
To learn more, see [Schematics Overview](guide/schematics) and [Schematics for Libraries](guide/schematics-for-libraries).
|
||||
|
||||
## Publishing your library
|
||||
|
||||
Use the Angular CLI and the npm package manager to build and publish your library as an npm package.
|
||||
|
||||
Before publishing a library to NPM, build it using the `--prod` flag which will use the older compiler and runtime known as View Engine instead of Ivy.
|
||||
|
||||
<code-example language="bash">
|
||||
ng build my-lib --prod
|
||||
cd dist/my-lib
|
||||
npm publish
|
||||
</code-example>
|
||||
|
||||
If you've never published a package in npm before, you must create a user account. Read more in [Publishing npm Packages](https://docs.npmjs.com/getting-started/publishing-npm-packages).
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
For now, it is not recommended to publish Ivy libraries to NPM because Ivy generated code is not backward compatible with View Engine, so apps using View Engine will not be able to consume them. Furthermore, the internal Ivy instructions are not yet stable, which can potentially break consumers using a different Angular version from the one used to build the library.
|
||||
|
||||
When a published library is used in an Ivy app, the Angular CLI will automatically convert it to Ivy using a tool known as the Angular compatibility compiler (`ngcc`). Thus, publishing your libraries using the View Engine compiler ensures that they can be transparently consumed by both View Engine and Ivy apps.
|
||||
|
||||
</div>
|
||||
|
||||
{@a lib-assets}
|
||||
|
||||
## Managing assets in a library
|
||||
|
||||
Starting with version 9.x of the [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) tool, you can configure the tool to automatically copy assets into your library package as part of the build process.
|
||||
You can use this feature when your library needs to publish optional theming files, Sass mixins, or documentation (like a changelog).
|
||||
|
||||
* Learn how to [copy assets into your library as part of the build](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md).
|
||||
|
||||
* Learn more about how to use the tool to [embed assets in CSS](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md).
|
||||
|
||||
|
||||
## Linked libraries
|
||||
|
||||
While working on a published library, you can use [npm link](https://docs.npmjs.com/cli/link) to avoid reinstalling the library on every build.
|
||||
|
||||
The library must be rebuilt on every change.
|
||||
When linking a library, make sure that the build step runs in watch mode, and that the library's `package.json` configuration points at the correct entry points.
|
||||
For example, `main` should point at a JavaScript file, not a TypeScript file.
|
||||
|
||||
## Use TypeScript path mapping for peer dependencies
|
||||
|
||||
Angular libraries should list all `@angular/*` dependencies as peer dependencies.
|
||||
This ensures that when modules ask for Angular, they all get the exact same module.
|
||||
If a library lists `@angular/core` in `dependencies` instead of `peerDependencies`, it might get a different Angular module instead, which would cause your application to break.
|
||||
|
||||
While developing a library, you must install all peer dependencies through `devDependencies` to ensure that the library compiles properly.
|
||||
A linked library will then have its own set of Angular libraries that it uses for building, located in its `node_modules` folder.
|
||||
However, this can cause problems while building or running your application.
|
||||
|
||||
To get around this problem you can use TypeScript path mapping to tell TypeScript that it should load some modules from a specific location.
|
||||
List all the peer dependencies that your library uses in the workspace TypeScript configuration file `./tsconfig.json`, and point them at the local copy in the app's `node_modules` folder.
|
||||
|
||||
```
|
||||
{
|
||||
"compilerOptions": {
|
||||
// ...
|
||||
// paths are relative to `baseUrl` path.
|
||||
"paths": {
|
||||
"@angular/*": [
|
||||
"./node_modules/@angular/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This mapping ensures that your library always loads the local copies of the modules it needs.
|
||||
|
||||
|
||||
## Using your own library in apps
|
||||
|
||||
You don't have to publish your library to the npm package manager in order to use it in your own apps, but you do have to build it first.
|
||||
|
||||
To use your own library in an app:
|
||||
|
||||
* Build the library. You cannot use a library before it is built.
|
||||
<code-example language="bash">
|
||||
ng build my-lib
|
||||
</code-example>
|
||||
|
||||
* In your apps, import from the library by name:
|
||||
```
|
||||
import { myExport } from 'my-lib';
|
||||
```
|
||||
|
||||
### Building and rebuilding your library
|
||||
|
||||
The build step is important if you haven't published your library as an npm package and then installed the package back into your app from npm.
|
||||
For instance, if you clone your git repository and run `npm install`, your editor will show the `my-lib` imports as missing if you haven't yet built your library.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
When you import something from a library in an Angular app, Angular looks for a mapping between the library name and a location on disk.
|
||||
When you install a library package, the mapping is in the `node_modules` folder. When you build your own library, it has to find the mapping in your `tsconfig` paths.
|
||||
|
||||
Generating a library with the Angular CLI automatically adds its path to the `tsconfig` file.
|
||||
The Angular CLI uses the `tsconfig` paths to tell the build system where to find the library.
|
||||
|
||||
</div>
|
||||
|
||||
If you find that changes to your library are not reflected in your app, your app is probably using an old build of the library.
|
||||
|
||||
You can rebuild your library whenever you make changes to it, but this extra step takes time.
|
||||
*Incremental builds* functionality improves the library-development experience.
|
||||
Every time a file is changed a partial build is performed that emits the amended files.
|
||||
|
||||
Incremental builds can be run as a background process in your dev environment. To take advantage of this feature add the `--watch` flag to the build command:
|
||||
|
||||
<code-example language="bash">
|
||||
ng build my-lib --watch
|
||||
</code-example>
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
The CLI `build` command uses a different builder and invokes a different build tool for libraries than it does for applications.
|
||||
|
||||
* The build system for apps, `@angular-devkit/build-angular`, is based on `webpack`, and is included in all new Angular CLI projects.
|
||||
* The build system for libraries is based on `ng-packagr`. It is only added to your dependencies when you add a library using `ng generate library my-lib`.
|
||||
|
||||
The two build systems support different things, and even where they support the same things, they do those things differently.
|
||||
This means that the TypeScript source can result in different JavaScript code in a built library than it would in a built application.
|
||||
|
||||
For this reason, an app that depends on a library should only use TypeScript path mappings that point to the *built library*.
|
||||
TypeScript path mappings should *not* point to the library source `.ts` files.
|
||||
|
||||
</div>
|
@ -1,13 +1,13 @@
|
||||
# Creating libraries
|
||||
# Creando librerías
|
||||
|
||||
This page provides a conceptual overview of how you can create and publish new libraries to extend Angular functionality.
|
||||
Está pagina provee una vista conceptual de como puedes crear y publicar nuevas librerías para extender las funcionalidades de Angular.
|
||||
|
||||
If you find that you need to solve the same problem in more than one app (or want to share your solution with other developers), you have a candidate for a library.
|
||||
A simple example might be a button that sends users to your company website, that would be included in all apps that your company builds.
|
||||
Si necesitas resolver el mismo problema en mas de una aplicación (o quiere compartir tu solución con otros desarrolladores), tienes un candidato para una librería.
|
||||
Un ejemplo simple puede ser un botón que envía a los usuarios hacia el sitio web de tu empresa, que sería incluido en todas las aplicaciones que tu empresa crea.
|
||||
|
||||
## Getting started
|
||||
## Empezando
|
||||
|
||||
Use the Angular CLI to generate a new library skeleton in a new workspace with the following commands.
|
||||
Usa el Angular CLI para generar un nuevo esqueleto de librería, en nuevo espacio de trabajo con los siguiente comandos.
|
||||
|
||||
<code-example language="bash">
|
||||
ng new my-workspace --create-application=false
|
||||
@ -15,18 +15,17 @@ Use the Angular CLI to generate a new library skeleton in a new workspace with t
|
||||
ng generate library my-lib
|
||||
</code-example>
|
||||
|
||||
The `ng generate` command creates the `projects/my-lib` folder in your workspace, which contains a component and a service inside an NgModule.
|
||||
El comando `ng generate` crea la carpeta `projects/my-lib` en el espacio de trabajo, que contiene un componente y un servicio dentro de un NgModule.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For more details on how a library project is structured, refer to the [Library project files](guide/file-structure#library-project-files) section of the [Project File Structure guide](guide/file-structure).
|
||||
Para más detalles sobre como una librería es estructurada, refiérase a los [Archivos de Librería](guide/file-structure#library-project-files) en la sección de [Guía de estructura de archivos](guide/file-structure).
|
||||
|
||||
You can use the monorepo model to use the same workspace for multiple projects.
|
||||
See [Setting up for a multi-project workspace](guide/file-structure#multiple-projects).
|
||||
Puedes usar un modelo de monorepo para usar el mismo espacio de trabajo con multiples proyectos. Véase [Configuración para espacio de trabajo multiproyecto](guide/file-structure#multiple-projects).
|
||||
|
||||
</div>
|
||||
|
||||
When you generate a new library, the workspace configuration file, `angular.json`, is updated with a project of type 'library'.
|
||||
Cuando se genera una nueva librería, el archivo de configuración del espacio de trabajo, `angular.json`, es actualizado con un proyecto de tipo 'library'.
|
||||
|
||||
<code-example format="json">
|
||||
"projects": {
|
||||
@ -42,7 +41,7 @@ When you generate a new library, the workspace configuration file, `angular.json
|
||||
...
|
||||
</code-example>
|
||||
|
||||
You can build, test, and lint the project with CLI commands:
|
||||
Puedes crear, probar y comprobar con los comandos de CLI:
|
||||
|
||||
<code-example language="bash">
|
||||
ng build my-lib
|
||||
@ -50,75 +49,78 @@ You can build, test, and lint the project with CLI commands:
|
||||
ng lint my-lib
|
||||
</code-example>
|
||||
|
||||
Notice that the configured builder for the project is different from the default builder for app projects.
|
||||
This builder, among other things, ensures that the library is always built with the [AOT compiler](guide/aot-compiler), without the need to specify the `--prod` flag.
|
||||
Puedes notar que el constructor configurado para el proyecto es diferente que el constructor por defecto para proyectos.
|
||||
El constructor, entre otras cosas, asegura que la librería siempre este construida con el [compilador AOT](guide/aot-compiler), sin la necesidad de especificar la bandera `--prod`.
|
||||
|
||||
To make library code reusable you must define a public API for it. This "user layer" defines what is available to consumers of your library. A user of your library should be able to access public functionality (such as NgModules, service providers and general utility functions) through a single import path.
|
||||
Para hacer el código de la librería reusable debes definir una API pública para ella. Esta "capa de usuario" define que esta disponible para los consumidores de tu librería. Un usuario de tu librería debería ser capaz de acceder a la funcionalidad publica (como NgModules, servicios, proveedores y en general funciones de utilidad) mediante una sola ruta.
|
||||
|
||||
The public API for your library is maintained in the `public-api.ts` file in your library folder.
|
||||
Anything exported from this file is made public when your library is imported into an application.
|
||||
Use an NgModule to expose services and components.
|
||||
La API pública para tu librería es mantenida en el archivo `public-api.ts` en tu carpeta de librería.
|
||||
Cualquier cosa exportada desde este archivo se hace publica cuando tu librería es importada dentro de una aplicación.
|
||||
Usa un NgModule para exponer los servicios y componentes.
|
||||
|
||||
Your library should supply documentation (typically a README file) for installation and maintenance.
|
||||
Tu libería debería suministrar documentatión (típicamente en el archivo README) para la instalación y mantenimiento.
|
||||
|
||||
## Refactoring parts of an app into a library
|
||||
## Refactorizando partes de una app dentro de un librería
|
||||
|
||||
To make your solution reusable, you need to adjust it so that it does not depend on app-specific code.
|
||||
Here are some things to consider in migrating application functionality to a library.
|
||||
Para hacer tu solución reusable, necesitas ajustarla para que no dependa del código específico de la aplicación.
|
||||
Aquí algunas cosas para considerar al migrar la funcionalidad de la aplicación a una librería.
|
||||
|
||||
* Declarations such as components and pipes should be designed as stateless, meaning they don’t rely on or alter external variables. If you do rely on state, you need to evaluate every case and decide whether it is application state or state that the library would manage.
|
||||
* Declaraciones tales como componentes y pipes deberían ser diseñados como 'stateless' (sin estado), lo que significa que no dependen ni alteran variables externas. Si tu dependes del estado, necesitas evaluar cada caso y decidir el estado de la aplicación o el estado que la aplicación administraría.
|
||||
|
||||
* Any observables that the components subscribe to internally should be cleaned up and disposed of during the lifecycle of those components.
|
||||
* Cualquier observable al cual los componentes se suscriban internamente deberían ser limpiados y desechados durante el ciclo de vida de esos componentes.
|
||||
|
||||
* Components should expose their interactions through inputs for providing context, and outputs for communicating events to other components.
|
||||
* Los componentes deberían exponer sus interacciones a través de 'inputs' para proporcionar contexto y 'outputs' para comunicar los eventos hacia otros componentes.
|
||||
|
||||
* Check all internal dependencies.
|
||||
* For custom classes or interfaces used in components or service, check whether they depend on additional classes or interfaces that also need to be migrated.
|
||||
* Similarly, if your library code depends on a service, that service needs to be migrated.
|
||||
* If your library code or its templates depend on other libraries (such as Angular Material, for instance), you must configure your library with those dependencies.
|
||||
* Verifique todas las dependencias internas.
|
||||
* Para clases personalizadas o interfaces usadas en componentes o servicios, verifique si dependen en clases adicionales o interfaces que también necesiten ser migradas.
|
||||
* Del mismo modo, si tu código de librería depende de un servicio, este servicio necesita ser migrado.
|
||||
* Si tu código de librería o sus plantillas dependen de otras librerías (como Angular Material), debes configurar tu librería con esas dependencias.
|
||||
|
||||
* Consider how you provide services to client applications.
|
||||
* Considere como proporcionar servicios a las aplicaciones cliente.
|
||||
|
||||
* Services should declare their own providers (rather than declaring providers in the NgModule or a component), so that they are *tree-shakable*. This allows the compiler to leave the service out of the bundle if it never gets injected into the application that imports the library. For more about this, see [Tree-shakable providers](guide/dependency-injection-providers#tree-shakable-providers).
|
||||
|
||||
* If you register global service providers or share providers across multiple NgModules, use the [`forRoot()` and `forChild()` design patterns](guide/singleton-services) provided by the [RouterModule](api/router/RouterModule).
|
||||
|
||||
* If your library provides optional services that might not be used by all client applications, support proper tree-shaking for that case by using the [lightweight token design pattern](guide/lightweight-injection-tokens).
|
||||
* Los servicios deberían declarar sus propios proveedores (en lugar de declarar los proveedores en el NgModule o en un componente). Esto le permite al compilador dejar los servicios fuera del 'bundle' si este nunca fue inyectado dentro de la aplicación que importa la librería, véase [proveedores Tree-shakable](guide/dependency-injection-providers#tree-shakable-providers)
|
||||
* Si registras proveedores globales o compartes proveedores a través de múltiples NgModules, usa el [`forRoot()` y `forChild()` como patrones de diseño](guide/singleton-services) proporcionados por el [RouterModule](api/router/RouterModule).
|
||||
* Si tu librería proporciona servicios opcionales que podrían no ser usados por todos las aplicaciones cliente, soporte apropiadamente el 'tree-shaking' para esos casos usando el [patrón de diseño de token ligero](guide/lightweight-injection-tokens).
|
||||
|
||||
{@a integrating-with-the-cli}
|
||||
|
||||
## Integrating with the CLI using code-generation schematics
|
||||
## Integración con el CLI usando generación de código con los schematics.
|
||||
|
||||
A library typically includes *reusable code* that defines components, services, and other Angular artifacts (pipes, directives, and so on) that you simply import into a project.
|
||||
A library is packaged into an npm package for publishing and sharing.
|
||||
This package can also include [schematics](guide/glossary#schematic) that provide instructions for generating or transforming code directly in your project, in the same way that the CLI creates a generic new component with `ng generate component`.
|
||||
A schematic that is packaged with a library can, for example, provide the Angular CLI with the information it needs to generate a component that configures and uses a particular feature, or set of features, defined in that library.
|
||||
One example of this is Angular Material's navigation schematic which configures the CDK's `BreakpointObserver` and uses it with Material's `MatSideNav` and `MatToolbar` components.
|
||||
Comúnmente una librería incluye *código reusable* que define componentes, servicios y otros Artefactos de Angular (pipes, directivas y etc.) que tu simplemente importas a un proyecto.
|
||||
Una librería es empaquetada dentro de un paquete npm para publicar y compartir.
|
||||
|
||||
You can create and include the following kinds of schematics.
|
||||
Este paquete también puede incluir [schematics](guide/glossary#schematic) que proporciona instrucciones para generar o transformar código directamente un tu proyecto, de la misma forma que el CLI crea un nuevo componente genérico con `ng generate component`.
|
||||
|
||||
* Include an installation schematic so that `ng add` can add your library to a project.
|
||||
Un 'schematic' empaquetado con una librería puede por ejemplo proporcionar al Angular CLI la información que necesita para generar un componente que configura y usa una particular característica o conjunto de características, definido en la librería.
|
||||
|
||||
* Include generation schematics in your library so that `ng generate` can scaffold your defined artifacts (components, services, tests, and so on) in a project.
|
||||
Un ejemplo de esto es el 'schematic' de navegación de Angular Material el cual configura los CDK's `BreakpointObserver` y lo usa con los componentes `MatSideNav` y `MatToolbar` de Angular Material.
|
||||
|
||||
* Include an update schematic so that `ng update` can update your library’s dependencies and provide migrations for breaking changes in new releases.
|
||||
Puedes crear e incluir los siguientes tipos de 'schematics'.
|
||||
|
||||
What you include in your library depends on your task.
|
||||
For example, you could define a schematic to create a dropdown that is pre-populated with canned data to show how to add it to an app.
|
||||
If you want a dropdown that would contain different passed-in values each time, your library could define a schematic to create it with a given configuration. Developers could then use `ng generate` to configure an instance for their own app.
|
||||
* Incluye un 'schematic' de instalación para que con `ng add` puedas agregar tu libería a un proyecto.
|
||||
|
||||
Suppose you want to read a configuration file and then generate a form based on that configuration.
|
||||
If that form will need additional customization by the developer who is using your library, it might work best as a schematic.
|
||||
However, if the forms will always be the same and not need much customization by developers, then you could create a dynamic component that takes the configuration and generates the form.
|
||||
In general, the more complex the customization, the more useful the schematic approach.
|
||||
* Incluye un 'schematic' de generación en tu librería para que con `ng generate` puedas hacer scaffolding de sus artefactos (componentes, servicios, pruebas y etc) en un proyecto.
|
||||
|
||||
To learn more, see [Schematics Overview](guide/schematics) and [Schematics for Libraries](guide/schematics-for-libraries).
|
||||
* Incluye un 'schematic' de actualización para que con `ng update` puedas actualizar las dependencias de tu librería y proporcionar migraciones para cambios importantes en un nuevo release.
|
||||
|
||||
## Publishing your library
|
||||
Lo que incluya tu librería depende de tu tarea.
|
||||
Por ejemplo, podrías definir un 'schematic' para crear un desplegable (dropdown) que esta pre-poblado con datos para mostrar como agregarlo a una aplicación.
|
||||
Si quieres un desplegable (dropdown) que contendrá valores diferentes cada vez, tu librería podría definir un 'schematic' para crearlo con una configuración dada. Los desarrolladores podrán entonces usar `ng generate` para configurar una instancia para sus propias aplicaciones.
|
||||
|
||||
Use the Angular CLI and the npm package manager to build and publish your library as an npm package.
|
||||
Supón que quieres leer un archivo de configuración y entonces generar una formulario con base a la configuración.
|
||||
Si este formulario necesita personalización adicional por parte del desarrollador que esta usando tu librería, esto podría trabajar mejor como un 'schematic'.
|
||||
Sin embargo, si el formulario siempre será el mismo y no necesita de mucha personalización por parte de los desarrolladores, entonces podría crear un componente dinámico que tome la configuración y genere el formulario.
|
||||
En general, entre más compleja sea personalización, la más util será en enfoque de un 'schematic'.
|
||||
|
||||
Before publishing a library to NPM, build it using the `--prod` flag which will use the older compiler and runtime known as View Engine instead of Ivy.
|
||||
Para aprender más, véase [Vista general de Schematics](guide/schematics) y [Schematics para librerías](guide/schematics-for-libraries).
|
||||
|
||||
{@a publishing-your-library}
|
||||
|
||||
## Publicando tu librería
|
||||
|
||||
Usa el Angular CLI y el gestor de paquetes npm para construir y publicar tu librería como un paquete npm.
|
||||
|
||||
Antes de publicar una librería a NPM, constrúyela usando la bandera `--prod` la cúal usará el compilador y tiempo de ejecución (runtime) más antiguos como 'View Engine' en vez de 'Ivy'.
|
||||
|
||||
<code-example language="bash">
|
||||
ng build my-lib --prod
|
||||
@ -126,48 +128,50 @@ cd dist/my-lib
|
||||
npm publish
|
||||
</code-example>
|
||||
|
||||
If you've never published a package in npm before, you must create a user account. Read more in [Publishing npm Packages](https://docs.npmjs.com/getting-started/publishing-npm-packages).
|
||||
Si nunca has publicado un paquete en npm antes, tu debes crear un cuenta. Lee más en [Publicando paquetes npm](https://docs.npmjs.com/getting-started/publishing-npm-packages).
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
For now, it is not recommended to publish Ivy libraries to NPM because Ivy generated code is not backward compatible with View Engine, so apps using View Engine will not be able to consume them. Furthermore, the internal Ivy instructions are not yet stable, which can potentially break consumers using a different Angular version from the one used to build the library.
|
||||
Por ahora, no es recomendando publicar librerías con Ivy hacia NPM por que Ivy genera código que no es retrocompatible con 'View Engine', entonces las aplicaciones usando 'View Engine' no podrán consumirlas. Además, las instrucciones internas de IVY no son estables aun, lo cual puede romper potencialmente a los consumidores que usan una diferente versión de Angular a la que uso para construir la libería.
|
||||
|
||||
When a published library is used in an Ivy app, the Angular CLI will automatically convert it to Ivy using a tool known as the Angular compatibility compiler (`ngcc`). Thus, publishing your libraries using the View Engine compiler ensures that they can be transparently consumed by both View Engine and Ivy apps.
|
||||
Cuando una librería publicada es usada en una aplicación con Ivy, el Angular CLI automáticamente la convertirá a Ivy usando una herramienta conocida como el compilador de compatibilidad Angular (`ngcc`). Por lo tanto, publicar tus librerías usado el compilador 'View Engine' garantiza que ellas puede ser consumidas de forma transparente por ambos motores 'View Engine' y 'Ivy'.
|
||||
|
||||
</div>
|
||||
|
||||
{@a lib-assets}
|
||||
|
||||
## Managing assets in a library
|
||||
## Gestionando activos (assets) en una librería.
|
||||
|
||||
Starting with version 9.x of the [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) tool, you can configure the tool to automatically copy assets into your library package as part of the build process.
|
||||
You can use this feature when your library needs to publish optional theming files, Sass mixins, or documentation (like a changelog).
|
||||
Desde la versión 9.x de la herramienta [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md), puedes configurar la herramienta para que automáticamente copie los activos (assets) dentro de el paquete de librería como parte del proceso de construcción.
|
||||
Puedes usar esta característica cuando tu librería necesite publicar archivos de temas opcionales, funciones de Sass o documentación (como un registro de cambios 'changelog').
|
||||
|
||||
* Learn how to [copy assets into your library as part of the build](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md).
|
||||
* Aprende como [copiar activos (assets) dentro de tu librería como parte de la construcción](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md).
|
||||
|
||||
* Learn more about how to use the tool to [embed assets in CSS](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md).
|
||||
* Aprende más acerca de como usar la herramienta para [incrustar activos (assets) de CSS](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md).
|
||||
|
||||
|
||||
## Linked libraries
|
||||
## Vinculando librerías
|
||||
|
||||
While working on a published library, you can use [npm link](https://docs.npmjs.com/cli/link) to avoid reinstalling the library on every build.
|
||||
Mientras trabajas en un librería publicada, puedes usar [npm link](https://docs.npmjs.com/cli/link) para evitar re instalar la librería en cada construcción.
|
||||
|
||||
The library must be rebuilt on every change.
|
||||
When linking a library, make sure that the build step runs in watch mode, and that the library's `package.json` configuration points at the correct entry points.
|
||||
For example, `main` should point at a JavaScript file, not a TypeScript file.
|
||||
La librería debe ser reconstruida en cada cambio.
|
||||
Cuando vinculas una librería, asegurate que el paso de construir corra en modo vigía (watch mode) y que el `package.json` de la librería configure los puntos de entrada correctos.
|
||||
Por ejemplo, `main` debería apuntar a un archivo JavaScript, no a un archivo TypeScript.
|
||||
|
||||
## Use TypeScript path mapping for peer dependencies
|
||||
## Utiliza el mapeo de rutas de TypeScript por las dependencias de pares.
|
||||
|
||||
Angular libraries should list all `@angular/*` dependencies as peer dependencies.
|
||||
This ensures that when modules ask for Angular, they all get the exact same module.
|
||||
If a library lists `@angular/core` in `dependencies` instead of `peerDependencies`, it might get a different Angular module instead, which would cause your application to break.
|
||||
Las librerías de Angular deben enumerar todas las dependencias `@angular/*` como dependencias de pares.
|
||||
Esto garantiza que cuando los módulos solicitan Angular, todos ellos obtienen exactamente el mismo módulo.
|
||||
Si tu librería lista `@angular/core` en `dependencies` en vez de en `peerDependencies`, podría obtener un módulo Angular diferente, lo qué haría que tu aplicación se rompiera.
|
||||
|
||||
While developing a library, you must install all peer dependencies through `devDependencies` to ensure that the library compiles properly.
|
||||
A linked library will then have its own set of Angular libraries that it uses for building, located in its `node_modules` folder.
|
||||
However, this can cause problems while building or running your application.
|
||||
Cuando desarrollas una librería, tu debes instalar todas las dependencias de pares mediante `devDependencies` para garantizar que la librería compile apropiadamente.
|
||||
Una librería vinculada tendrá su propio conjunto de librerías Angular que usa para construir, ubicados en su carpeta `node_modules`.
|
||||
|
||||
To get around this problem you can use TypeScript path mapping to tell TypeScript that it should load some modules from a specific location.
|
||||
List all the peer dependencies that your library uses in the workspace TypeScript configuration file `./tsconfig.json`, and point them at the local copy in the app's `node_modules` folder.
|
||||
Sin embargo, esto puede causar problemas mientras construyes o corres tu aplicación.
|
||||
|
||||
Para evitar este problema tu puedes usar el mapeo de rutas de TypeScript para indicarle a TypeScript que este debería cargar algunos módulos desde una ubicación especifica.
|
||||
|
||||
Enumera todas las dependencias de pares que tu librería usa en el archivo de configuración `./tsconfig.json` del espacio de trabajo de TypeScript, y apúntalos a la copia local en la carpeta `node_modules` de la aplicación.
|
||||
|
||||
```
|
||||
{
|
||||
@ -183,47 +187,47 @@ List all the peer dependencies that your library uses in the workspace TypeScrip
|
||||
}
|
||||
```
|
||||
|
||||
This mapping ensures that your library always loads the local copies of the modules it needs.
|
||||
Este mapeador garantiza que tu librería siempre cargue las copias locales del módulo que necesita.
|
||||
|
||||
|
||||
## Using your own library in apps
|
||||
## Usando tu propia librería en aplicaciones.
|
||||
|
||||
You don't have to publish your library to the npm package manager in order to use it in your own apps, but you do have to build it first.
|
||||
No tienes que publicar tu librería hacia el gestor de paquetes npm para usarla en tus propias aplicaciones, pero tienes que construirla primero.
|
||||
|
||||
To use your own library in an app:
|
||||
Para usar tu propia librería en tu aplicación:
|
||||
|
||||
* Build the library. You cannot use a library before it is built.
|
||||
* Construye la librería. No puedes usar una librería antes que se construya.
|
||||
<code-example language="bash">
|
||||
ng build my-lib
|
||||
</code-example>
|
||||
|
||||
* In your apps, import from the library by name:
|
||||
* En tus aplicaciones, importa la librería por el nombre:
|
||||
```
|
||||
import { myExport } from 'my-lib';
|
||||
```
|
||||
|
||||
### Building and rebuilding your library
|
||||
### Construyendo y re construyendo tu librería.
|
||||
|
||||
The build step is important if you haven't published your library as an npm package and then installed the package back into your app from npm.
|
||||
For instance, if you clone your git repository and run `npm install`, your editor will show the `my-lib` imports as missing if you haven't yet built your library.
|
||||
El paso de construir es importante si no tienes publicada tu librería como un paquete npm y luego ha instalado el paquete de nuevo dentro tu aplicación desde npm.
|
||||
Por ejemplo, si clonas tu repositorio git y corres `npm install`, tu editor mostrará la importación de `my-lib` como perdida si no tienes aun construida tu librería.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
When you import something from a library in an Angular app, Angular looks for a mapping between the library name and a location on disk.
|
||||
When you install a library package, the mapping is in the `node_modules` folder. When you build your own library, it has to find the mapping in your `tsconfig` paths.
|
||||
Cuando importas algo desde una librería en una aplicación Angular, Angular busca un mapeo entre el nombre de librería y una ubicación en disco.
|
||||
Cuando instalas un paquete de librería, el mapeo esta en la carpeta `node_modules`. Cuando construyes tu propia librería, tiene que encontrar el mapeo en tus rutas de `tsconfig`.
|
||||
|
||||
Generating a library with the Angular CLI automatically adds its path to the `tsconfig` file.
|
||||
The Angular CLI uses the `tsconfig` paths to tell the build system where to find the library.
|
||||
Generando una librería con el Angular CLI automáticamente agrega su ruta en el archivo `tsconfig`.
|
||||
El Angular CLI usa las rutas `tsconfig` para indicarle al sistema construido donde encontrar la librería.
|
||||
|
||||
</div>
|
||||
|
||||
If you find that changes to your library are not reflected in your app, your app is probably using an old build of the library.
|
||||
Si descubres que los cambios en tu librería no son reflejados en tu aplicación, tu aplicación probablemente esta usando una construcción antigua de la librería.
|
||||
|
||||
You can rebuild your library whenever you make changes to it, but this extra step takes time.
|
||||
*Incremental builds* functionality improves the library-development experience.
|
||||
Every time a file is changed a partial build is performed that emits the amended files.
|
||||
Puedes re construir tu librería cada vez que hagas cambios en esta, pero este paso extra toma tiempo.
|
||||
Las *construcciones incrementales* funcionalmente mejoran la experiencia de desarrollo de librerías.
|
||||
Cada vez que un archivo es cambiando una construcción parcial es realizada y esta emite los archivos modificados.
|
||||
|
||||
Incremental builds can be run as a background process in your dev environment. To take advantage of this feature add the `--watch` flag to the build command:
|
||||
Las *Construcciones incrementales* puede ser ejecutadas como un proceso en segundo plano en tu entorno de desarrollo. Para aprovechar esta característica agrega la bandera `--watch` al comando de construcción:
|
||||
|
||||
<code-example language="bash">
|
||||
ng build my-lib --watch
|
||||
@ -231,15 +235,15 @@ ng build my-lib --watch
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
The CLI `build` command uses a different builder and invokes a different build tool for libraries than it does for applications.
|
||||
El comando `build` del CLI utiliza un constructor diferente e invoca una herramienta de construcción diferente para las librerías que para las aplicaciones.
|
||||
|
||||
* The build system for apps, `@angular-devkit/build-angular`, is based on `webpack`, and is included in all new Angular CLI projects.
|
||||
* The build system for libraries is based on `ng-packagr`. It is only added to your dependencies when you add a library using `ng generate library my-lib`.
|
||||
* El sistema de construcción para aplicaciones, `@angular-devkit/build-angular`, esta basado en `webpack`, y esta incluida en todos los nuevos proyectos de Angular CLI.
|
||||
* El sistema de construcción esta basado en `ng-packagr`. Este es solo agregado en tus dependencias cuando agregas una librería usando `ng generate library my-lib`.
|
||||
|
||||
The two build systems support different things, and even where they support the same things, they do those things differently.
|
||||
This means that the TypeScript source can result in different JavaScript code in a built library than it would in a built application.
|
||||
Los dos sistemas de construcción soportan diferentes cosas e incluso si ellos soportan las mismas cosas, ellos hacen esas cosas de forma diferente.
|
||||
Esto quiere decir que la fuente de TypeScript puede generar en código JavaScript diferente en una librería construida que en una aplicación construida.
|
||||
|
||||
For this reason, an app that depends on a library should only use TypeScript path mappings that point to the *built library*.
|
||||
TypeScript path mappings should *not* point to the library source `.ts` files.
|
||||
Por esta razón, una aplicación que depende de una librería debería solo usar el mapeo de rutas de TypeScript que apunte a la *librería construida*.
|
||||
El mapeo de rutas de TypeScript no debería apuntar hacia los archivos `.ts` fuente de la librería.
|
||||
|
||||
</div>
|
||||
|
104
aio/content/guide/feature-modules.en.md
Normal file
104
aio/content/guide/feature-modules.en.md
Normal file
@ -0,0 +1,104 @@
|
||||
# Feature modules
|
||||
|
||||
Feature modules are NgModules for the purpose of organizing code.
|
||||
|
||||
For the final sample app with a feature module that this page describes,
|
||||
see the <live-example></live-example>.
|
||||
|
||||
<hr>
|
||||
|
||||
As your app grows, you can organize code relevant for a specific feature.
|
||||
This helps apply clear boundaries for features. With feature modules,
|
||||
you can keep code related to a specific functionality or feature
|
||||
separate from other code. Delineating areas of your
|
||||
app helps with collaboration between developers and teams, separating
|
||||
directives, and managing the size of the root module.
|
||||
|
||||
## Feature modules vs. root modules
|
||||
|
||||
A feature module is an organizational best practice, as opposed to a concept of the core Angular API. A feature module delivers a cohesive set of functionality focused on a
|
||||
specific application need such as a user workflow, routing, or forms.
|
||||
While you can do everything within the root module, feature modules
|
||||
help you partition the app into focused areas. A feature module
|
||||
collaborates with the root module and with other modules through
|
||||
the services it provides and the components, directives, and
|
||||
pipes that it shares.
|
||||
|
||||
## How to make a feature module
|
||||
|
||||
Assuming you already have an app that you created with the [Angular CLI](cli), create a feature
|
||||
module using the CLI by entering the following command in the
|
||||
root project directory. Replace `CustomerDashboard` with the
|
||||
name of your module. You can omit the "Module" suffix from the name because the CLI appends it:
|
||||
|
||||
```sh
|
||||
ng generate module CustomerDashboard
|
||||
|
||||
```
|
||||
|
||||
This causes the CLI to create a folder called `customer-dashboard` with a file inside called `customer-dashboard.module.ts` with the following contents:
|
||||
|
||||
```typescript
|
||||
import { NgModule } from "@angular/core";
|
||||
import { CommonModule } from "@angular/common";
|
||||
|
||||
@NgModule({
|
||||
imports: [CommonModule],
|
||||
declarations: [],
|
||||
})
|
||||
export class CustomerDashboardModule {}
|
||||
```
|
||||
|
||||
The structure of an NgModule is the same whether it is a root module or a feature module. In the CLI generated feature module, there are two JavaScript import statements at the top of the file: the first imports `NgModule`, which, like the root module, lets you use the `@NgModule` decorator; the second imports `CommonModule`, which contributes many common directives such as `ngIf` and `ngFor`. Feature modules import `CommonModule` instead of `BrowserModule`, which is only imported once in the root module. `CommonModule` only contains information for common directives such as `ngIf` and `ngFor` which are needed in most templates, whereas `BrowserModule` configures the Angular app for the browser which needs to be done only once.
|
||||
|
||||
The `declarations` array is available for you to add declarables, which
|
||||
are components, directives, and pipes that belong exclusively to this particular module. To add a component, enter the following command at the command line where `customer-dashboard` is the directory where the CLI generated the feature module and `CustomerDashboard` is the name of the component:
|
||||
|
||||
```sh
|
||||
ng generate component customer-dashboard/CustomerDashboard
|
||||
|
||||
```
|
||||
|
||||
This generates a folder for the new component within the customer-dashboard folder and updates the feature module with the `CustomerDashboardComponent` info:
|
||||
|
||||
<code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard.module.ts" region="customer-dashboard-component" header="src/app/customer-dashboard/customer-dashboard.module.ts"></code-example>
|
||||
|
||||
The `CustomerDashboardComponent` is now in the JavaScript import list at the top and added to the `declarations` array, which lets Angular know to associate this new component with this feature module.
|
||||
|
||||
## Importing a feature module
|
||||
|
||||
To incorporate the feature module into your app, you have to let the root module, `app.module.ts`, know about it. Notice the `CustomerDashboardModule` export at the bottom of `customer-dashboard.module.ts`. This exposes it so that other modules can get to it. To import it into the `AppModule`, add it to the imports in `app.module.ts` and to the `imports` array:
|
||||
|
||||
<code-example path="feature-modules/src/app/app.module.ts" region="app-module" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
Now the `AppModule` knows about the feature module. If you were to add any service providers to the feature module, `AppModule` would know about those too, as would any other feature modules. However, NgModules don’t expose their components.
|
||||
|
||||
## Rendering a feature module’s component template
|
||||
|
||||
When the CLI generated the `CustomerDashboardComponent` for the feature module, it included a template, `customer-dashboard.component.html`, with the following markup:
|
||||
|
||||
<code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard/customer-dashboard.component.html" region="feature-template" header="src/app/customer-dashboard/customer-dashboard/customer-dashboard.component.html"></code-example>
|
||||
|
||||
To see this HTML in the `AppComponent`, you first have to export the `CustomerDashboardComponent` in the `CustomerDashboardModule`. In `customer-dashboard.module.ts`, just beneath the `declarations` array, add an `exports` array containing `CustomerDashboardComponent`:
|
||||
|
||||
<code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard.module.ts" region="component-exports" header="src/app/customer-dashboard/customer-dashboard.module.ts"></code-example>
|
||||
|
||||
Next, in the `AppComponent`, `app.component.html`, add the tag `<app-customer-dashboard>`:
|
||||
|
||||
<code-example path="feature-modules/src/app/app.component.html" region="app-component-template" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Now, in addition to the title that renders by default, the `CustomerDashboardComponent` template renders too:
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/feature-modules/feature-module.png" alt="feature module component">
|
||||
</div>
|
||||
|
||||
<hr />
|
||||
|
||||
## More on NgModules
|
||||
|
||||
You may also be interested in the following:
|
||||
|
||||
- [Lazy Loading Modules with the Angular Router](guide/lazy-loading-ngmodules).
|
||||
- [Providers](guide/providers).
|
||||
- [Types of Feature Modules](guide/module-types).
|
@ -1,106 +1,79 @@
|
||||
# Feature modules
|
||||
# Módulos de funcionalidades
|
||||
|
||||
Feature modules are NgModules for the purpose of organizing code.
|
||||
Los módulos de funcionalidades son NgModules con el propósito de organizar el código.
|
||||
|
||||
For the final sample app with a feature module that this page describes,
|
||||
see the <live-example></live-example>.
|
||||
Para la aplicación de muestra final con un módulo de funcionalidades que se describe en esta página,
|
||||
ver el <live-example> </live-example>.
|
||||
|
||||
<hr>
|
||||
|
||||
As your app grows, you can organize code relevant for a specific feature.
|
||||
This helps apply clear boundaries for features. With feature modules,
|
||||
you can keep code related to a specific functionality or feature
|
||||
separate from other code. Delineating areas of your
|
||||
app helps with collaboration between developers and teams, separating
|
||||
directives, and managing the size of the root module.
|
||||
A medida que tu aplicación crece, puedes organizar el código relevante para una funcionalidad específica. Esto ayuda a aplicar límites claros para las funcionalidades. Con módulos de funcionalidades,
|
||||
puedes mantener el código relacionado con una funcionalidad o característica específica
|
||||
separado de otro código. Delinear áreas de suaplicación ayuda con la colaboración entre desarrolladores y equipos, separando directivas y gestionar el tamaño del módulo raíz.
|
||||
|
||||
## Módulos de funcionalidades frente a módulos raíz
|
||||
|
||||
## Feature modules vs. root modules
|
||||
Un módulo de funcionalidades es una mejor práctica organizativa, a diferencia de un concepto de la API angular principal. Un módulo de funcionalidades ofrece un conjunto coherente de funcionalidades centradas en una necesidad de aplicación específica, como un flujo de trabajo, enrutamiento o formularios de usuario. Si bien puede hacer todo dentro del módulo raíz, los módulos de funcionalidades lo ayudan a dividir la aplicación en áreas específicas. Un módulo de funcionalidades colabora con el módulo raíz y con otros módulos a través de los servicios que proporciona y los componentes, directivas y canalizaciones que comparte.
|
||||
|
||||
A feature module is an organizational best practice, as opposed to a concept of the core Angular API. A feature module delivers a cohesive set of functionality focused on a
|
||||
specific application need such as a user workflow, routing, or forms.
|
||||
While you can do everything within the root module, feature modules
|
||||
help you partition the app into focused areas. A feature module
|
||||
collaborates with the root module and with other modules through
|
||||
the services it provides and the components, directives, and
|
||||
pipes that it shares.
|
||||
## Cómo hacer un módulo de funcionalidades
|
||||
|
||||
## How to make a feature module
|
||||
|
||||
Assuming you already have an app that you created with the [Angular CLI](cli), create a feature
|
||||
module using the CLI by entering the following command in the
|
||||
root project directory. Replace `CustomerDashboard` with the
|
||||
name of your module. You can omit the "Module" suffix from the name because the CLI appends it:
|
||||
Suponiendo que ya tienes una aplicación que creó con la [CLI Angular](cli), crea un módulo de funcionalidades usando la CLI ingresando el siguiente comando en el directorio raíz del proyecto. Reemplaza `CustomerDashboard` con el nombre de tu módulo. Puedes omitir el sufijo "Módulo" / "Module" del nombre porque la CLI lo agrega:
|
||||
|
||||
```sh
|
||||
ng generate module CustomerDashboard
|
||||
|
||||
```
|
||||
|
||||
|
||||
This causes the CLI to create a folder called `customer-dashboard` with a file inside called `customer-dashboard.module.ts` with the following contents:
|
||||
Esto hace que la CLI cree una carpeta llamada `customer-dashboard` con un archivo dentro llamado` customer-dashboard.module.ts` con el siguiente contenido:
|
||||
|
||||
```typescript
|
||||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule
|
||||
],
|
||||
declarations: []
|
||||
imports: [CommonModule],
|
||||
declarations: [],
|
||||
})
|
||||
export class CustomerDashboardModule { }
|
||||
export class CustomerDashboardModule {}
|
||||
```
|
||||
|
||||
The structure of an NgModule is the same whether it is a root module or a feature module. In the CLI generated feature module, there are two JavaScript import statements at the top of the file: the first imports `NgModule`, which, like the root module, lets you use the `@NgModule` decorator; the second imports `CommonModule`, which contributes many common directives such as `ngIf` and `ngFor`. Feature modules import `CommonModule` instead of `BrowserModule`, which is only imported once in the root module. `CommonModule` only contains information for common directives such as `ngIf` and `ngFor` which are needed in most templates, whereas `BrowserModule` configures the Angular app for the browser which needs to be done only once.
|
||||
La estructura de un NgModule es la misma si es un módulo raíz o un módulo de funcionalidades. En el módulo de funcionalidades generado por CLI, hay dos declaraciones de importación de JavaScript en la parte superior del archivo: la primera importa `NgModule`, que, como el módulo raíz, le permite usar el decorador `@NgModule`; el segundo importa `CommonModule`, que aporta muchas directivas comunes como `ngIf` y `ngFor`. Los módulos de funcionalidades importan `CommonModule` en lugar de `BrowserModule`, que solo se importa una vez en el módulo raíz. `CommonModule` solo contiene información para directivas comunes como `ngIf` y `ngFor` que se necesitan en la mayoría de las plantillas, mientras que `BrowserModule` configura la aplicación Angular para el navegador, lo cual debe hacerse solo una vez.
|
||||
|
||||
The `declarations` array is available for you to add declarables, which
|
||||
are components, directives, and pipes that belong exclusively to this particular module. To add a component, enter the following command at the command line where `customer-dashboard` is the directory where the CLI generated the feature module and `CustomerDashboard` is the name of the component:
|
||||
La matriz `declaraciones` está disponible para que agregue declarables, que son componentes, directivas y canalizaciones que pertenecen exclusivamente a este módulo en particular. Para agregar un componente, ingresa el siguiente comando en la línea de comando donde `customer-dashboard` es el directorio donde la CLI generó el módulo de funciones y CustomerDashboard` es el nombre del componente:
|
||||
|
||||
```sh
|
||||
ng generate component customer-dashboard/CustomerDashboard
|
||||
|
||||
```
|
||||
|
||||
This generates a folder for the new component within the customer-dashboard folder and updates the feature module with the `CustomerDashboardComponent` info:
|
||||
|
||||
Esto genera una carpeta para el nuevo componente dentro de la carpeta del panel del cliente y actualiza el módulo de funcionalidades con la información de `CustomerDashboardComponent`:
|
||||
|
||||
<code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard.module.ts" region="customer-dashboard-component" header="src/app/customer-dashboard/customer-dashboard.module.ts"></code-example>
|
||||
|
||||
El `CustomerDashboardComponent` ahora se encuentra en la lista de importación de JavaScript en la parte superior y se agregó a la matriz de `declaraciones`, lo que le permite a Angular asociar este nuevo componente con este módulo de funciones.
|
||||
|
||||
## Importación de un módulo de funcionalidades
|
||||
|
||||
The `CustomerDashboardComponent` is now in the JavaScript import list at the top and added to the `declarations` array, which lets Angular know to associate this new component with this feature module.
|
||||
|
||||
## Importing a feature module
|
||||
|
||||
To incorporate the feature module into your app, you have to let the root module, `app.module.ts`, know about it. Notice the `CustomerDashboardModule` export at the bottom of `customer-dashboard.module.ts`. This exposes it so that other modules can get to it. To import it into the `AppModule`, add it to the imports in `app.module.ts` and to the `imports` array:
|
||||
Para incorporar el módulo de funcionalidades en tu aplicación, debes informar al módulo raíz, `app.module.ts`. Observa la exportación de "CustomerDashboardModule" en la parte inferior de `customer-dashboard.module.ts`. Esto lo expone para que otros módulos puedan acceder a él. Para importarlo en el `AppModule`, agrégalo a las importaciones en` app.module.ts` y al arreglo de `import`:
|
||||
|
||||
<code-example path="feature-modules/src/app/app.module.ts" region="app-module" header="src/app/app.module.ts"></code-example>
|
||||
|
||||
Ahora el `AppModule` conoce el módulo de funcionalidades. Si tuviera que agregar cualquier proveedor de servicios al módulo de funcionalidades, `AppModule` también lo conocería, al igual que cualquier otro módulo de funcionalidades. Sin embargo, los NgModules no exponen sus componentes.
|
||||
|
||||
Now the `AppModule` knows about the feature module. If you were to add any service providers to the feature module, `AppModule` would know about those too, as would any other feature modules. However, NgModules don’t expose their components.
|
||||
## Representación de la plantilla de componente de un módulo de funcionalidades
|
||||
|
||||
|
||||
## Rendering a feature module’s component template
|
||||
|
||||
When the CLI generated the `CustomerDashboardComponent` for the feature module, it included a template, `customer-dashboard.component.html`, with the following markup:
|
||||
Cuando la CLI generó el `CustomerDashboardComponent` para el módulo de funcionalidades, incluyó una plantilla, `customer-dashboard.component.html`, con el siguiente marcado:
|
||||
|
||||
<code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard/customer-dashboard.component.html" region="feature-template" header="src/app/customer-dashboard/customer-dashboard/customer-dashboard.component.html"></code-example>
|
||||
|
||||
|
||||
To see this HTML in the `AppComponent`, you first have to export the `CustomerDashboardComponent` in the `CustomerDashboardModule`. In `customer-dashboard.module.ts`, just beneath the `declarations` array, add an `exports` array containing `CustomerDashboardComponent`:
|
||||
Para ver este HTML en el `AppComponent`, primero tienes que exportar el `CustomerDashboardComponent` en el `CustomerDashboardModule`. En `customer-dashboard.module.ts`, justo debajo de la matriz de `declaraciones`, agrega una matriz de `exportaciones` que contenga `CustomerDashboardComponent`:
|
||||
|
||||
<code-example path="feature-modules/src/app/customer-dashboard/customer-dashboard.module.ts" region="component-exports" header="src/app/customer-dashboard/customer-dashboard.module.ts"></code-example>
|
||||
|
||||
|
||||
|
||||
Next, in the `AppComponent`, `app.component.html`, add the tag `<app-customer-dashboard>`:
|
||||
Luego, en el `AppComponent`, `app.component.html`, agrega la etiqueta `<app-customer-dashboard>`:
|
||||
|
||||
<code-example path="feature-modules/src/app/app.component.html" region="app-component-template" header="src/app/app.component.html"></code-example>
|
||||
|
||||
|
||||
Now, in addition to the title that renders by default, the `CustomerDashboardComponent` template renders too:
|
||||
Ahora, además del título que se representa de forma predeterminada, la plantilla `CustomerDashboardComponent` también se representa:
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/feature-modules/feature-module.png" alt="feature module component">
|
||||
@ -108,9 +81,10 @@ Now, in addition to the title that renders by default, the `CustomerDashboardCom
|
||||
|
||||
<hr />
|
||||
|
||||
## More on NgModules
|
||||
## Más sobre NgModules
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Lazy Loading Modules with the Angular Router](guide/lazy-loading-ngmodules).
|
||||
* [Providers](guide/providers).
|
||||
* [Types of Feature Modules](guide/module-types).
|
||||
También te puede interesar lo siguiente:
|
||||
|
||||
- [Módulos de carga diferida con el enrutador angular](guide/lazy-loading-ngmodules).
|
||||
- [Proveedores](guide/providers).
|
||||
- [Tipos de módulos de funciones](guide/module-types).
|
||||
|
@ -22,7 +22,7 @@ Una estructura que proporciona metadatos para una clase. Ver [decorador](#decora
|
||||
|
||||
Es una herramienta que utiliza la CLI para realizar tareas complejas, como la compilación y la ejecución de pruebas, de acuerdo con una configuración proporcionada.
|
||||
|
||||
El architect es un shell que ejecuta un [constructor](#builder) (definido en un [paquete npm](#npm-package)) con una [configuración de destino] dada (#target).
|
||||
El architect es un shell que ejecuta un [constructor](#builder) (definido en un [paquete npm](#npm-package)) con una [configuración de destino](#target) dada.
|
||||
|
||||
En el [archivo de configuración del espacio de trabajo](guide/workspace-config#project-tool-configuration-options), una sección de "architect" proporciona opciones de configuración para los architects constructores.
|
||||
|
||||
@ -37,20 +37,6 @@ Un archivo especifica los archivos raíz y las opciones de compilación necesari
|
||||
|
||||
{@a B}
|
||||
|
||||
{@a library}
|
||||
|
||||
## biblioteca
|
||||
|
||||
En Angular, un [proyecto](#project) que proporciona funcionalidad que se puede incluir en otras aplicaciones de Angular.
|
||||
Una biblioteca no es una aplicación Angular completa y no puede ejecutarse de forma independiente.
|
||||
Para agregar funcionalidades reutilizables de Angular a aplicaciones web no construidas con Angular, puedes usar Angular [elementos personalizados](#angular-element).)
|
||||
|
||||
- Los desarrolladores de bibliotecas pueden usar la [Angular CLI](#cli) para `generar` andamios para una nueva biblioteca en un [espacio de trabajo](#workspace) existente, y pueden publicar una biblioteca como un paquete `npm`.
|
||||
|
||||
- Los desarrolladores de aplicaciones pueden usar la [Angular CLI](#cli) para `agregar` una biblioteca publicada para usar con una aplicación en el mismo [espacio de trabajo](#workspace).
|
||||
|
||||
Ver también [esquema](#schematic).
|
||||
|
||||
{@a bootstrap}
|
||||
|
||||
## bootstrap
|
||||
@ -119,15 +105,15 @@ La compilación ahead-of-time (AOT) de Angular convierte el código Angular HTML
|
||||
|
||||
Este es el mejor modo de compilación para entornos de producción, con un menor tiempo de carga y un mayor rendimiento en comparación con [compilación just-in-time (JIT)](#jit).
|
||||
|
||||
Al compilar su aplicación utilizando la herramienta de línea de comandos `ngc`, puede iniciar directamente a una module factory, por lo que no necesita incluir el compilador Angular en su paquete de JavaScript.
|
||||
Al compilar tu aplicación utilizando la herramienta de línea de comandos `ngc`, puedes iniciar directamente a una module factory, por lo que no necesitas incluir el compilador Angular en tu paquete de JavaScript.
|
||||
|
||||
{@a jit}
|
||||
|
||||
## compilación just-in-time (JIT)
|
||||
|
||||
El compilador Angular just-in-time (JIT) convierte su código Angular HTML y TypeScript en código JavaScript eficiente en tiempo de ejecución, como parte del arranque.
|
||||
El compilador Angular just-in-time (JIT) convierte tu código Angular HTML y TypeScript en código JavaScript eficiente en tiempo de ejecución, como parte del arranque.
|
||||
|
||||
La compilación JIT es el valor predeterminado (a diferencia de la compilación AOT) cuando ejecuta los comandos CLI `ng build` y`ng serve` de Angular, y es una buena opción durante el desarrollo.
|
||||
La compilación JIT es el valor predeterminado (a diferencia de la compilación AOT) cuando ejecutas los comandos CLI `ng build` y`ng serve` de Angular, y es una buena opción durante el desarrollo.
|
||||
El modo JIT no se recomienda para el uso en producción porque da como resultado grandes cargas útiles de aplicaciones que dificultan el rendimiento de arranque.
|
||||
|
||||
Comparar con [compilación ahead-of-time (AOT)](#aot).
|
||||
@ -202,10 +188,10 @@ El detector de cambios es responsable de actualizar la vista para reflejar el mo
|
||||
Del mismo modo, el usuario puede interactuar con la interfaz de usuario, lo que provoca eventos que cambian el estado del modelo de datos.
|
||||
Estos eventos pueden desencadenar la detección de cambios.
|
||||
|
||||
Usando la estrategia de detección de cambio predeterminada ("CheckAlways"), el detector de cambio pasa por la [jerarquía de vista](#view-tree) en cada turno de VM para verificar cada [propiedad vinculada a datos](#data-binding) en la plantilla. en el modelo. En la primera fase, compara el estado actual de los datos dependientes con el estado anterior y recopila los cambios.
|
||||
Usando la estrategia de detección de cambio predeterminada ("CheckAlways"), el detector de cambio pasa por la [jerarquía de vista](#view-tree) en cada turno de VM para verificar cada [propiedad vinculada a datos](#data-binding) en la plantilla. En la primera fase, compara el estado actual de los datos dependientes con el estado anterior y recopila los cambios.
|
||||
En la segunda fase, actualiza la página DOM para reflejar los nuevos valores de datos.
|
||||
|
||||
Si configuras la estrategia de detección de cambios `OnPush` ("CheckOnce"), el detector de cambios se ejecuta solo cuando [invocado explícitamente](api/core/ChangeDetectorRef), o cuando se activa mediante un cambio de referencia en mediante un `Input` o un controlador de eventos. Esto generalmente mejora el rendimiento. Para obtener más información, consulta [Optimizar la detección de cambios de Angular](https://web.dev/faster-angular-change-detection/).
|
||||
Si configuras la estrategia de detección de cambios `OnPush` ("CheckOnce"), el detector de cambios se ejecuta solo cuando es [invocado explícitamente](api/core/ChangeDetectorRef), o cuando se activa mediante un cambio de referencia en mediante un `Input` o un controlador de eventos. Esto generalmente mejora el rendimiento. Para obtener más información, consulta [Optimizar la detección de cambios de Angular](https://web.dev/faster-angular-change-detection/).
|
||||
|
||||
{@a class-decorator}
|
||||
|
||||
@ -241,7 +227,7 @@ Obtén más información en [Directivas de atributos](guide/attribute-directives
|
||||
|
||||
## directivas estructurales
|
||||
|
||||
Una categoría de [directiva](#directive) que es responsable de dar forma al diseño HTML modificando DOM y mdashthat, es decir, agregando, eliminando o manipulando elementos y sus elementos secundarios.
|
||||
Una categoría de [directiva](#directive) que es responsable de dar forma al diseño HTML modificando el DOM, es decir, agregando, eliminando o manipulando elementos y sus elementos secundarios.
|
||||
|
||||
Obtén más información en [Directivas estructurales](guide/structural-directives).
|
||||
|
||||
@ -277,7 +263,7 @@ Consulta [decorador de clase](#class-decorator), [decorador de campo de clase](#
|
||||
|
||||
## directiva
|
||||
|
||||
Una clase que puede modificar la estructura del DOM o modificar atributos en el DOM y el modelo de datos de componentes. Una definición de clase directiva está precedida inmediatamente por un `@Directive()` [decorador](#decorator) que proporciona metadatos.
|
||||
Una clase que puede modificar la estructura del DOM o modificar atributos en el DOM y el modelo de datos de componentes. Una definición de clase directiva está precedida inmediatamente por un [decorador](#decorator) `@Directive()` que proporciona metadatos.
|
||||
|
||||
Una clase de directiva generalmente está asociada con un elemento o atributo HTML, y ese elemento o atributo a menudo se conoce como la directiva misma. Cuando Angular encuentra una directiva en una [plantilla](#template) HTML, crea la instancia de clase de directiva coincidente y le da a la instancia control sobre esa parte del DOM del navegador.
|
||||
|
||||
@ -290,8 +276,8 @@ Hay tres categorías de directivas:
|
||||
- [Directivas estructurales](#structural-directive) modifican la estructura del DOM.
|
||||
|
||||
Angular proporciona una serie de directivas integradas que comienzan con el prefijo `ng`.
|
||||
También puede crear nuevas directivas para implementar su propia funcionalidad.
|
||||
Asocia un _selector_ (una etiqueta HTML como `<my-directive>`) con una directiva personalizada, extendiendo así la [sintaxis de plantilla](guide/template-syntax) que puede usar en sus aplicaciones.
|
||||
También puedes crear nuevas directivas para implementar tu propia funcionalidad.
|
||||
Asocia un _selector_ (una etiqueta HTML como `<my-directive>`) con una directiva personalizada, extendiendo así la [sintaxis de plantilla](guide/template-syntax) que puede usar en tus aplicaciones.
|
||||
|
||||
{@a E}
|
||||
|
||||
@ -301,15 +287,15 @@ Asocia un _selector_ (una etiqueta HTML como `<my-directive>`) con una directiva
|
||||
|
||||
La [especificación oficial del lenguaje JavaScript](https://es.wikipedia.org/wiki/ECMAScript).
|
||||
|
||||
No todos los navegadores son compatibles con el último estándar ECMAScript, pero puede usar un [transpiler](#transpile) (como [TypeScript](#typescript)) para escribir código utilizando las últimas funciones, que luego se transpilarán al código que se ejecuta en las versiones que son compatibles con los navegadores.
|
||||
No todos los navegadores son compatibles con el último estándar ECMAScript, pero puedes usar un [transpiler](#transpile) (como [TypeScript](#typescript)) para escribir código utilizando las últimas funciones, que luego se transpilarán al código que se ejecuta en las versiones que son compatibles con los navegadores.
|
||||
|
||||
Para obtener más información, consultá [Browser Support](guide/browser-support).
|
||||
Para obtener más información, consulta [Browser Support](guide/browser-support).
|
||||
|
||||
{@a binding}
|
||||
|
||||
## enlaces (binding)
|
||||
|
||||
En general, es la práctica de establecer una variable o propiedad en un valor de datos Dentro de Angular, generalmente se refiere a [enlace de datos](#data-binding), que coordina las propiedades del objeto DOM con las propiedades del objeto de datos.
|
||||
En general, es la práctica de establecer una variable o propiedad en un valor de datos. Dentro de Angular, generalmente se refiere a [enlace de datos](#data-binding), que coordina las propiedades del objeto DOM con las propiedades del objeto de datos.
|
||||
|
||||
A veces se refiere a una [inyección de dependencia](#dependency-injection) de enlace
|
||||
entre un [token](#token) y una dependencia de [proveedor](#provider).
|
||||
@ -354,7 +340,7 @@ Una herramienta que configura e implementa la navegación entre estados y [vista
|
||||
|
||||
El módulo `Router` es un [NgModule](#ngmodule) que proporciona los proveedores de servicios y las directivas necesarias para navegar por las vistas de la aplicación. Un [componente de enrutamiento](#router-outlet) es aquel que importa el módulo `Router` y cuya plantilla contiene un elemento `RouterOutlet` donde puede mostrar vistas producidas por el enrutador.
|
||||
|
||||
El enrutador define la navegación entre vistas en una sola página, a diferencia de la navegación entre páginas. Interpreta enlaces de tipo URL para determinar qué vistas crear o destruir, y qué componentes cargar o descargar. Le permite aprovechar [carga diferida](#lazy-load) en las aplicaciones Angular.
|
||||
A diferencia de la navegación entre páginas, el enrutador define la navegación entre vistas en una sola página. Interpreta enlaces de tipo URL para determinar qué vistas crear o destruir, y qué componentes cargar o descargar. Te permite aprovechar la [carga diferida](#lazy-load) en las aplicaciones Angular.
|
||||
|
||||
Obtén más información en [Enrutamiento y navegación](guide/router).
|
||||
|
||||
@ -367,7 +353,7 @@ En la mayoría de los casos, esto le permite usar plantillas de Angular y enlace
|
||||
|
||||
La documentación generalmente se refiere a _elementos_ (instancias `ElementRef`), a diferencia de _elementos DOM_ (que se puede acceder directamente si es necesario).
|
||||
|
||||
Comparado con [elemento personalizado](#custom-element).
|
||||
Comparar con [elemento personalizado](#custom-element).
|
||||
|
||||
{@a angular-element}
|
||||
|
||||
@ -395,17 +381,17 @@ Consulta también [carga de componentes dinámicos](#dynamic-components).
|
||||
|
||||
## esquema
|
||||
|
||||
Una biblioteca de andamios que define cómo generar o transformar un proyecto de programación creando, modificando, refactorizando o moviendo archivos y códigos.
|
||||
Una librería de andamios que define cómo generar o transformar un proyecto de programación creando, modificando, refactorizando o moviendo archivos y códigos.
|
||||
Un esquema define [reglas](#rule) que operan en un sistema de archivos virtual llamado [árbol](#file-tree).
|
||||
|
||||
La [Angular CLI](#cli) utiliza esquemas para generar y modificar [proyectos Angular](#project) y partes de proyectos.
|
||||
|
||||
- Angular proporciona un conjunto de esquemas para usar con la CLI. Consulta la [Referencia de comando de Angular CLI](cli). El comando [`ng add`](cli/add) ejecuta esquemas como parte de agregar una biblioteca a su proyecto. El comando [`ng generate`](cli/generate) ejecuta esquemas para crear aplicaciones, bibliotecas y construcciones de código Angular.
|
||||
- Angular proporciona un conjunto de esquemas para usar con la CLI. Consulta la [Referencia de comando de Angular CLI](cli). El comando [`ng add`](cli/add) ejecuta esquemas como parte de agregar una librería a su proyecto. El comando [`ng generate`](cli/generate) ejecuta esquemas para crear aplicaciones, librerías y construcciones de código Angular.
|
||||
|
||||
- Los desarrolladores de [Bibliotecas](#library) pueden crear esquemas que permitan a la Angular CLI agregar y actualizar sus bibliotecas publicadas y generar artefactos que la biblioteca defina.
|
||||
Agregue estos esquemas al paquete npm que usa para publicar y compartir su biblioteca.
|
||||
- Los desarrolladores de [Librerías](#library) pueden crear esquemas que permitan a la Angular CLI agregar y actualizar sus blibrerías publicadas y generar artefactos que la librería defina.
|
||||
Agregue estos esquemas al paquete npm que usa para publicar y compartir su librería.
|
||||
|
||||
Obtén más información en [Esquemas](guide/schematics) e [Integración de bibliotecas con la CLI](guide/creating-libraries#integrating-with-the-cli).
|
||||
Obtén más información en [Esquemas](guide/schematics) e [Integración de librerías con la CLI](guide/creating-libraries#integrating-with-the-cli).
|
||||
|
||||
{@a schematics-cli}
|
||||
|
||||
@ -418,17 +404,17 @@ Usando Node 6.9 o superior, instala la CLI de esquemas globalmente:
|
||||
npm install -g @angular-devkit/schematics-cli
|
||||
</code-example>
|
||||
|
||||
Esto instala el ejecutable `schematics`, que puede usar para crear un nuevo esquema [colección](#collection) con un esquema inicial llamado. La carpeta de colección es un espacio de trabajo para esquemas. También puede usar el comando `schematics` para agregar un nuevo esquema a una colección existente, o extender un esquema existente.
|
||||
Esto instala el ejecutable `schematics`, que puedes usar para crear un nuevo esquema [colección](#collection) con un esquema inicial llamado. La carpeta de colección es un espacio de trabajo para esquemas. También puedes usar el comando `schematics` para agregar un nuevo esquema a una colección existente, o extender un esquema existente.
|
||||
|
||||
{@a workspace}
|
||||
|
||||
## espacio de trabajo
|
||||
|
||||
Una colección de [proyectos](#project) Angular (es decir, aplicaciones y bibliotecas) con tecnología de [anglar CLI](#cli) que generalmente se ubican en un único repositorio de control de fuente (como [git](https://git-scm.com/)).
|
||||
Una colección de [proyectos](#project) Angular (es decir, aplicaciones y librerías) con tecnología de [Angular CLI](#cli) que generalmente se ubican en un único repositorio de control de fuente (como [git](https://git-scm.com/)).
|
||||
|
||||
El [CLI](#cli) [`ng new` command](cli/new) crea un directorio del sistema de archivos (la "raíz del espacio de trabajo"). En la raíz del espacio de trabajo, también crea el espacio de trabajo [archivo de configuración](#configuration) (`angular.json`) y, por defecto, un proyecto de aplicación inicial con el mismo nombre.
|
||||
El [comando CLI `ng new`](cli/new) crea un directorio del sistema de archivos (la "raíz del espacio de trabajo"). En la raíz del espacio de trabajo, también crea el espacio de trabajo [archivo de configuración](#configuration) (`angular.json`) y, por defecto, un proyecto de aplicación inicial con el mismo nombre.
|
||||
|
||||
Los comandos que crean u operan en aplicaciones y bibliotecas (como `add` y `generate`) deben ejecutarse desde una carpeta de espacio de trabajo.
|
||||
Los comandos que crean u operan en aplicaciones y librerías (como `add` y `generate`) deben ejecutarse desde una carpeta de espacio de trabajo.
|
||||
|
||||
Para obtener más información, consulta [Configuración del espacio de trabajo](guide/workspace-config).
|
||||
|
||||
@ -471,9 +457,9 @@ Cuando se usan formularios reactivos:
|
||||
- La validación se configura mediante funciones de validación en lugar de directivas de validación.
|
||||
- Cada control se crea explícitamente en la clase de componente creando una instancia de `FormControl` manualmente o con `FormBuilder`.
|
||||
- Los elementos de entrada de la plantilla _no_ usan `ngModel`.
|
||||
- as directivas Angular asociadas tienen el prefijo `form`, como `formControl`, `formGroup` y `formControlName`.
|
||||
- Las directivas Angular asociadas tienen el prefijo `form`, como `formControl`, `formGroup` y `formControlName`.
|
||||
|
||||
La alternativa es un formulario basado en plantillas. Para una introducción y comparación de ambos enfoques de formularios, consulte [Introducción a los formularios Angular](guide/forms-overview).
|
||||
La alternativa es un formulario basado en plantillas. Para una introducción y comparación de ambos enfoques de formularios, consulta [Introducción a los formularios Angular](guide/forms-overview).
|
||||
|
||||
{@a unidirectional-data-flow}
|
||||
|
||||
@ -484,9 +470,9 @@ Un modelo de flujo de datos donde el árbol de componentes siempre se verifica e
|
||||
En la práctica, esto significa que los datos en Angular fluyen hacia abajo durante la detección de cambios.
|
||||
Un componente primario puede cambiar fácilmente los valores en sus componentes secundarios porque primero se verifica el primario.
|
||||
Sin embargo, podría producirse un error si un componente secundario intenta cambiar un valor en su elemento primario durante la detección de cambio (invirtiendo el flujo de datos esperado), porque el componente principal ya se ha procesado.
|
||||
En modo de desarrollo, Angular arroja el error `ExpressionChangedAfterItHasBeenCheckedError` si su aplicación intenta hacer esto, en lugar de fallar silenciosamente en representar el nuevo valor.
|
||||
En modo de desarrollo, Angular arroja el error `ExpressionChangedAfterItHasBeenCheckedError` si tu aplicación intenta hacer esto, en lugar de fallar silenciosamente en representar el nuevo valor.
|
||||
|
||||
Para evitar este error, un método [lifecycle hook](guide/lifecycle-hooks)que busca realizar dicho cambio debería desencadenar una nueva ejecución de detección de cambio. La nueva ejecución sigue la misma dirección que antes, pero logra recoger el nuevo valor.
|
||||
Para evitar este error, un método [lifecycle hook](guide/lifecycle-hooks) que busca realizar dicho cambio debería desencadenar una nueva ejecución de detección de cambio. La nueva ejecución sigue la misma dirección que antes, pero logra recoger el nuevo valor.
|
||||
|
||||
{@a G}
|
||||
|
||||
@ -522,10 +508,10 @@ Obtén más información en [Inyección de dependencia en Angular](guide/depende
|
||||
|
||||
## interfaz de línea de comandos (CLI)
|
||||
|
||||
[Angular CLI](cli) es una herramienta de línea de comandos para administrar el ciclo de desarrollo Angular. Úsalo para crear la estructura inicial del sistema de archivos para un [espacio de trabajo](#workspace) o [proyecto](#project), y para ejecutar [esquemas](#schematic) que agregue y modifique código para versiones genéricas iniciales de varios elementos. La CLI admite todas las etapas del ciclo de desarrollo, incluidas la construcción, las pruebas, la agrupación y la implementación.
|
||||
[Angular CLI](cli) es una herramienta de línea de comandos para administrar el ciclo de desarrollo Angular. Úsalo para crear la estructura inicial del sistema de archivos para un [espacio de trabajo](#workspace) o [proyecto](#project), y para ejecutar [esquemas](#schematic) que agreguen y modifiquen código para versiones genéricas iniciales de varios elementos. La CLI admite todas las etapas del ciclo de desarrollo, incluidas la construcción, las pruebas, la agrupación y la implementación.
|
||||
|
||||
- Para comenzar a usar la CLI para un nuevo proyecto, consultá [Configuración del entorno local](guide/setup-local "Configuración para el desarrollo local").
|
||||
- Para obtener más información sobre las capacidades completas de la CLI, consultá la [Referencia del comando CLI](cli).
|
||||
- Para comenzar a usar la CLI para un nuevo proyecto, consulta [Configuración del entorno local](guide/setup-local "Configuración para el desarrollo local").
|
||||
- Para obtener más información sobre las capacidades completas de la CLI, consulta la [Referencia del comando CLI](cli).
|
||||
|
||||
Ver también [Esquemas CLI](#schematics-cli).
|
||||
|
||||
@ -533,13 +519,13 @@ Ver también [Esquemas CLI](#schematics-cli).
|
||||
|
||||
## inmutabilidad
|
||||
|
||||
La capacidad de alterar el estado de un valor después de su creación. [Formularios reactivos](#reactive-forms) realizan cambios inmutables en ese cada cambio en el modelo de datos produce un nuevo modelo de datos en lugar de modificar el existente. [Formas controladas por plantilla](#template-driven-forms) realizan cambios mutables con `NgModel` y [enlace de datos bidireccional](#data-binding) para modificar el modelo de datos existente en su lugar.
|
||||
La capacidad de alterar el estado de un valor después de su creación. [Formularios reactivos](#reactive-forms) realizan cambios inmutables en ese cada cambio en el modelo de datos produce un nuevo modelo de datos en lugar de modificar el existente. [Formularios controlados por plantilla](#template-driven-forms) realizan cambios mutables con `NgModel` y [enlace de datos bidireccional](#data-binding) para modificar el modelo de datos existente en su lugar.
|
||||
|
||||
{@a injectable}
|
||||
|
||||
## inyectable
|
||||
|
||||
Una clase Angular u otra definición que proporciona una dependencia utilizando el mecanismo de [inyección de dependencia](#di). Una clase inyectable [servicio](#service) debe estar marcada por el `@Injectable()` [decorador](#decorator). Otros elementos, como valores constantes, también pueden ser inyectables.
|
||||
Una clase Angular u otra definición que proporciona una dependencia utilizando el mecanismo de [inyección de dependencia](#di). Una clase inyectable de [servicio](#service) debe estar marcada por el [decorador](#decorator) `@Injectable()`. Otros elementos, como valores constantes, también pueden ser inyectables.
|
||||
|
||||
{@a injector}
|
||||
|
||||
@ -604,9 +590,23 @@ La jerarquía de vistas no implica una jerarquía de componentes. Las vistas que
|
||||
|
||||
## lenguaje específico de dominio (DSL)
|
||||
|
||||
Una biblioteca o API de propósito especial; consulte [Idioma específico del dominio](https://es.wikipedia.org/wiki/Lenguaje_espec%C3%ADfico_de_dominio).
|
||||
Una librería o API de propósito especial; consulte [lenguaje específico del dominio](https://es.wikipedia.org/wiki/Lenguaje_espec%C3%ADfico_de_dominio).
|
||||
Angular extiende TypeScript con lenguajes específicos de dominio para varios dominios relevantes para aplicaciones Angular, definidas en NgModules como [animaciones](guide/animations), [formularios](guide/forms), y [enrutamiento y navegación](guide/router).
|
||||
|
||||
{@a library}
|
||||
|
||||
## Librerías
|
||||
|
||||
En Angular, un [proyecto](#project) que proporciona funcionalidad que se puede incluir en otras aplicaciones de Angular.
|
||||
Una librería no es una aplicación Angular completa y no puede ejecutarse de forma independiente.
|
||||
Para agregar funcionalidades reutilizables de Angular a aplicaciones web no construidas con Angular, puedes usar Angular [elementos personalizados](#angular-element).)
|
||||
|
||||
- Los desarrolladores de librerías pueden usar la [Angular CLI](#cli) para `generar` andamios para una nueva librería en un [espacio de trabajo](#workspace) existente, y pueden publicar una librería como un paquete `npm`.
|
||||
|
||||
- Los desarrolladores de aplicaciones pueden usar la [Angular CLI](#cli) para `agregar` una librería publicada para usar con una aplicación en el mismo [espacio de trabajo](#workspace).
|
||||
|
||||
Ver también [esquema](#schematic).
|
||||
|
||||
{@a lifecycle-hook}
|
||||
|
||||
## lifecycle hook
|
||||
@ -635,7 +635,7 @@ Obtén más información en [Lifecycle Hooks](guide/lifecycle-hooks).
|
||||
|
||||
## modelo de formulario
|
||||
|
||||
La "fuente de verdad" para el valor y el estado de validación de un elemento de entrada de formulario en un momento dado. Cuando se usan [formularios reactivos](#reactive-forms), tel modelo de formulario se crea explícitamente en la clase de componente. Al utilizar [formularios controlados por plantilla](#template-driven-forms), el modelo de formulario se crea implícitamente mediante directivas.
|
||||
La "fuente de verdad" para el valor y el estado de validación de un elemento de entrada de formulario en un momento dado. Cuando se usan [formularios reactivos](#reactive-forms), el modelo de formulario se crea explícitamente en la clase de componente. Al utilizar [formularios controlados por plantilla](#template-driven-forms), el modelo de formulario se crea implícitamente mediante directivas.
|
||||
|
||||
Obtén más información sobre los formularios reactivos y basados en plantillas en [Introducción a los formularios en Angular](guide/forms-overview).
|
||||
|
||||
@ -647,7 +647,7 @@ En general, un módulo recopila un bloque de código dedicado a un solo propósi
|
||||
|
||||
En JavaScript (ECMAScript), cada archivo es un módulo y todos los objetos definidos en el archivo pertenecen a ese módulo. Los objetos se pueden exportar, haciéndolos públicos, y los objetos públicos se pueden importar para su uso por otros módulos.
|
||||
|
||||
Angular se envía como una colección de módulos JavaScript (también llamados bibliotecas). Cada nombre de biblioteca Angular comienza con el prefijo `@angular`. Instala bibliotecas Angular con el [administrador de paquetes npm](https://docs.npmjs.com/getting-started/what-is-npm) e importa partes de ellas con las declaraciones de JavaScript `import`.
|
||||
Angular se envía como una colección de módulos JavaScript (también llamados librerías). Cada nombre de librería Angular comienza con el prefijo `@angular`. Instala librerías Angular con el [administrador de paquetes npm](https://docs.npmjs.com/getting-started/what-is-npm) e importa partes de ellas con las declaraciones de JavaScript `import`.
|
||||
|
||||
Comparar con [NgModule](#ngmodule).
|
||||
|
||||
@ -658,7 +658,7 @@ Comparar con [NgModule](#ngmodule).
|
||||
## ngcc
|
||||
|
||||
Compilador de compatibilidad Angular.
|
||||
Si se crea la aplicación usando [Ivy](#ivy), pero depende de las bibliotecas que no se han compilado con Ivy, la CLI usa `ngcc` para actualizar automáticamente las bibliotecas dependientes para usar Ivy.
|
||||
Si se crea la aplicación usando [Ivy](#ivy), pero depende de las librerías que no se han compilado con Ivy, la CLI usa `ngcc` para actualizar automáticamente las librerías dependientes para usar Ivy.
|
||||
|
||||
{@a ngmodule}
|
||||
|
||||
@ -669,7 +669,7 @@ Una definición de clase precedida por el `@NgModule()` [decorador](#decorator),
|
||||
Al igual que un [módulo JavaScript](#module), un NgModule puede exportar la funcionalidad para que otros NgModules la usen e importar la funcionalidad pública de otros NgModules.
|
||||
Los metadatos para una clase NgModule recopilan componentes, directivas y canalizaciones que la aplicación usa junto con la lista de importaciones y exportaciones. Ver también [declarable](#declarable).
|
||||
|
||||
Los NgModules generalmente llevan el nombre del archivo en el que se define lo exportado. Por ejemplo, la clase Angular [DatePipe](api/common/DatePipe) pertenece a un módulo de características llamado `date_pipe` en el archivo`date_pipe.ts`. Se importa desde un [paquete con scope](#scoped-package) como `@angular/core`.
|
||||
Los NgModules generalmente llevan el nombre del archivo en el que se define lo exportado. Por ejemplo, la clase [DatePipe](api/common/DatePipe) de Angular pertenece a un módulo de características llamado `date_pipe` en el archivo`date_pipe.ts`. Se importa desde un [paquete con scope](#scoped-package) como `@angular/core`.
|
||||
|
||||
Cada aplicación Angular tiene un módulo raíz. Por convención, la clase se llama `AppModule` y reside en un archivo llamado `app.module.ts`.
|
||||
|
||||
@ -685,7 +685,7 @@ Un productor de múltiples valores, que empuja a [suscriptores](#subscriber). Se
|
||||
|
||||
Los observables pueden entregar valores únicos o múltiples de cualquier tipo a los suscriptores, ya sea sincrónicamente (como una función entrega un valor a la persona que llama) o en un horario. Un suscriptor recibe una notificación de los nuevos valores a medida que se producen y una notificación de finalización normal o finalización de error.
|
||||
|
||||
Angular utiliza una biblioteca de terceros llamada [Extensiones reactivas (RxJS)](http://reactivex.io/rxjs/).
|
||||
Angular utiliza una librería de terceros llamada [Extensiones reactivas (RxJS)](http://reactivex.io/rxjs/).
|
||||
|
||||
Obtén más información en [Observables](guide/observables).
|
||||
|
||||
@ -701,7 +701,7 @@ Un objeto pasado al método `subscribe()` para un [observable](#observable). El
|
||||
|
||||
## paquete npm
|
||||
|
||||
El [administrador de paquetes npm](https://docs.npmjs.com/getting-started/what-is-npm) se usa para distribuir y cargar módulos y bibliotecas Angular.
|
||||
El [administrador de paquetes npm](https://docs.npmjs.com/getting-started/what-is-npm) se usa para distribuir y cargar módulos y librerías Angular.
|
||||
|
||||
Obtén más información acerca de cómo Angular usa [Paquetes npm](guide/npm-packages).
|
||||
|
||||
@ -763,7 +763,7 @@ Consulta [Soporte del navegador](guide/browser-support) para ver polyfills que a
|
||||
|
||||
## proyecto
|
||||
|
||||
En la Angular CLI, una aplicación independiente o [biblioteca](#library) que se puede crear o modificar mediante un comando de la CLI.
|
||||
En la Angular CLI, una aplicación independiente o [librería](#library) que se puede crear o modificar mediante un comando de la CLI.
|
||||
|
||||
Un proyecto, generado por [`ng new`](cli/new), contiene el conjunto de archivos de origen, recursos y archivos de configuración que necesita para desarrollar y probar la aplicación utilizando la CLI. Los proyectos también se pueden crear con los comandos `ng generate application` y `ng generate library`.
|
||||
|
||||
@ -777,7 +777,7 @@ El archivo [`angular.json`](guide/workspace-config) configura todos los proyecto
|
||||
|
||||
Una forma de insertar contenido DOM desde fuera de un componente en la vista del componente en un lugar designado.
|
||||
|
||||
Para obtener más información, consultá [Respuesta a cambios en el contenido](guide/lifecycle-hooks#content-projection).
|
||||
Para obtener más información, consulta [Respuesta a cambios en el contenido](guide/lifecycle-hooks#content-projection).
|
||||
|
||||
{@a provider}
|
||||
|
||||
|
37
aio/content/guide/libraries.en.md
Normal file
37
aio/content/guide/libraries.en.md
Normal file
@ -0,0 +1,37 @@
|
||||
# Overview of Angular libraries
|
||||
|
||||
Many applications need to solve the same general problems, such as presenting a unified user interface, presenting data, and allowing data entry.
|
||||
Developers can create general solutions for particular domains that can be adapted for re-use in different apps.
|
||||
Such a solution can be built as Angular *libraries* and these libraries can be published and shared as *npm packages*.
|
||||
|
||||
An Angular library is an Angular [project](guide/glossary#project) that differs from an app in that it cannot run on its own.
|
||||
A library must be imported and used in an app.
|
||||
|
||||
Libraries extend Angular's base functionality. For example, to add [reactive forms](guide/reactive-forms) to an app, add the library package using `ng add @angular/forms`, then import the `ReactiveFormsModule` from the `@angular/forms` library in your application code.
|
||||
Similarly, adding the [service worker](guide/service-worker-intro) library to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) (PWA).
|
||||
[Angular Material](https://material.angular.io/) is an example of a large, general-purpose library that provides sophisticated, reusable, and adaptable UI components.
|
||||
|
||||
Any app developer can use these and other libraries that have been published as npm packages by the Angular team or by third parties. See [Using Published Libraries](guide/using-libraries).
|
||||
|
||||
## Creating libraries
|
||||
|
||||
If you have developed functionality that is suitable for reuse, you can create your own libraries.
|
||||
These libraries can be used locally in your workspace, or you can publish them as [npm packages](guide/npm-packages) to share with other projects or other Angular developers.
|
||||
These packages can be published to the npm registry, a private npm Enterprise registry, or a private package management system that supports npm packages.
|
||||
See [Creating Libraries](guide/creating-libraries).
|
||||
|
||||
Whether you decide to package functionality as a library is an architectural decision, similar to deciding whether a piece of functionality is a component or a service, or deciding on the scope of a component.
|
||||
|
||||
Packaging functionality as a library forces the artifacts in the library to be decoupled from the application's business logic.
|
||||
This can help to avoid various bad practices or architecture mistakes that can make it difficult to decouple and reuse code in the future.
|
||||
|
||||
Putting code into a separate library is more complex than simply putting everything in one app.
|
||||
It requires more of an investment in time and thought for managing, maintaining, and updating the library.
|
||||
This complexity can pay off, however, when the library is being used in multiple apps.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Note that libraries are intended to be used by Angular apps.
|
||||
To add Angular functionality to non-Angular web apps, you can use [Angular custom elements](guide/elements).
|
||||
|
||||
</div>
|
@ -1,37 +1,38 @@
|
||||
# Overview of Angular libraries
|
||||
# Vista general de librerías para Angular
|
||||
|
||||
Many applications need to solve the same general problems, such as presenting a unified user interface, presenting data, and allowing data entry.
|
||||
Developers can create general solutions for particular domains that can be adapted for re-use in different apps.
|
||||
Such a solution can be built as Angular *libraries* and these libraries can be published and shared as *npm packages*.
|
||||
Muchas aplicaciones necesitan resolver los mismos problemas en general, como presentar una interfaz de usuario unificada, mostrar datos, permitir entrada de datos etc.
|
||||
Los desarrolladores puede crear soluciones generales para dominios particulares que pueden ser adoptados para re usarse en diferentes aplicaciones.
|
||||
Tal solución se puede construir como *librerías* para Angular y estas librerías pueden ser publicadas y compartidas como *paquetes de npm*.
|
||||
|
||||
An Angular library is an Angular [project](guide/glossary#project) that differs from an app in that it cannot run on its own.
|
||||
A library must be imported and used in an app.
|
||||
Una librería de Angular es como un [proyecto](guide/glossary#project) lo que la diferencia de una app es que no puede correr por si sola.
|
||||
Una librería debe ser importada y usada en una app.
|
||||
|
||||
Libraries extend Angular's base functionality. For example, to add [reactive forms](guide/reactive-forms) to an app, add the library package using `ng add @angular/forms`, then import the `ReactiveFormsModule` from the `@angular/forms` library in your application code.
|
||||
Similarly, adding the [service worker](guide/service-worker-intro) library to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) (PWA).
|
||||
[Angular Material](https://material.angular.io/) is an example of a large, general-purpose library that provides sophisticated, reusable, and adaptable UI components.
|
||||
Las librerías extienden la funcionalidad base de Angular. Por ejemplo, para agregar [formularios reactivos](guide/reactive-forms) en una app, agregamos la librería usando `ng add @angular/forms`, entonces importamos el `ReactiveFormsModule` desde la librería `@angular/forms` el código de la aplicación.
|
||||
De igual manera, agregar la librería [service worker](guide/service-worker-intro) dentro de una aplicación Angular es el primer paso para convertir una aplicación a una [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) (PWA).
|
||||
[Angular Material](https://material.angular.io/) es un ejemplo de una gran librería de propósito general que ofrece componentes de UI sofisticados, reutilizables y adaptables.
|
||||
|
||||
Any app developer can use these and other libraries that have been published as npm packages by the Angular team or by third parties. See [Using Published Libraries](guide/using-libraries).
|
||||
Cualquier desarrollador de apps puede usar estas y otras librerías que han sido publicadas como paquetes de npm por el equipo de Angular o por terceros. Mirá [Usando librerías publicadas](guide/using-libraries).
|
||||
|
||||
## Creating libraries
|
||||
## Creando librerías
|
||||
|
||||
If you have developed functionality that is suitable for reuse, you can create your own libraries.
|
||||
These libraries can be used locally in your workspace, or you can publish them as [npm packages](guide/npm-packages) to share with other projects or other Angular developers.
|
||||
These packages can be published to the npm registry, a private npm Enterprise registry, or a private package management system that supports npm packages.
|
||||
See [Creating Libraries](guide/creating-libraries).
|
||||
Si tu tienes funcionalidades desarrolladas que puede ser adecuadas para re usarse tu puedes crear tus propias librerías.
|
||||
Estas librerías puede ser usadas localmente en tu espacio de trabajo, o puede ser publicadas como [paquetes de npm](guide/npm-packages) para compartir con otros proyectos o otros desarrolladores Angular.
|
||||
Estos paquetes pueden ser publicados en el registro de npm, en un registro empresarial privado de npm, o en un sistema de gestión de paquetes privado que soporte paquetes de npm.
|
||||
Mirá [Creando librerías](guide/creating-libraries).
|
||||
|
||||
Whether you decide to package functionality as a library is an architectural decision, similar to deciding whether a piece of functionality is a component or a service, or deciding on the scope of a component.
|
||||
Si tu decides empaquetar una funcionalidad como una librería es una decisión de arquitectura, similar a decidir entre si una pieza de funcionalidad es un componente o un servicio, o decidir el alcance de un componente.
|
||||
|
||||
Packaging functionality as a library forces the artifacts in the library to be decoupled from the application's business logic.
|
||||
This can help to avoid various bad practices or architecture mistakes that can make it difficult to decouple and reuse code in the future.
|
||||
Empaquetar funcionalidad como una librería fuerza a
|
||||
que los artefactos en la librería puedan ser desacoplados de la lógica de negocio de la aplicación.
|
||||
Esto puede ayudar a evitar varias malas practicas o errores de arquitectura que puede hacer difícil desacoplar y re usar código en el futuro.
|
||||
|
||||
Putting code into a separate library is more complex than simply putting everything in one app.
|
||||
It requires more of an investment in time and thought for managing, maintaining, and updating the library.
|
||||
This complexity can pay off, however, when the library is being used in multiple apps.
|
||||
Poniendo el código dentro de una librería separada es más complejo que simplemente poner todo en una sola aplicación.
|
||||
Esto requiere una inversión mayor de tiempo y pensar para administrar, mantener y actualizar la librería.
|
||||
Sin embargo esta complejidad puede valer la pena cuando la librería esta siendo usada en múltiples aplicaciones.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Note that libraries are intended to be used by Angular apps.
|
||||
To add Angular functionality to non-Angular web apps, you can use [Angular custom elements](guide/elements).
|
||||
Note que las librerías están destinadas para ser usadas por aplicaciones Angular.
|
||||
Para agregar funcionalidad de Angular hacia una aplicación web que no es Angular, puedes usar [Angular custom elements](guide/elements).
|
||||
|
||||
</div>
|
||||
</div>
|
56
aio/content/guide/migration-solution-style-tsconfig.en.md
Normal file
56
aio/content/guide/migration-solution-style-tsconfig.en.md
Normal file
@ -0,0 +1,56 @@
|
||||
# Solution-style `tsconfig.json` migration
|
||||
|
||||
## What does this migration do?
|
||||
|
||||
This migration adds support to existing projects for TypeScript's new ["solution-style" tsconfig feature](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#solution-style-tsconfig).
|
||||
|
||||
Support is added by making two changes:
|
||||
|
||||
1. Renaming the workspace-level `tsconfig.json` to `tsconfig.base.json`.
|
||||
All project [TypeScript configuration files](guide/typescript-configuration) will extend from this base which contains the common options used throughout the workspace.
|
||||
|
||||
2. Adding the solution `tsconfig.json` file at the root of the workspace.
|
||||
This `tsconfig.json` file will only contain references to project-level TypeScript configuration files and is only used by editors/IDEs.
|
||||
|
||||
As an example, the solution `tsconfig.json` for a new project is as follows:
|
||||
|
||||
```json
|
||||
// This is a "Solution Style" tsconfig.json file, and is used by editors and TypeScript’s language server to improve development experience.
|
||||
// It is not intended to be used to perform a compilation.
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
},
|
||||
{
|
||||
"path": "./e2e/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Why is this migration necessary?
|
||||
|
||||
Solution-style `tsconfig.json` files provide an improved editing experience and fix several long-standing defects when editing files in an IDE.
|
||||
IDEs that leverage the TypeScript language service (for example, [Visual Studio Code](https://code.visualstudio.com)), will only use TypeScript configuration files that are named `tsconfig.json`.
|
||||
In complex projects, there may be more than one compilation unit and each of these units may have different settings and options.
|
||||
|
||||
With the Angular CLI, a project will have application code that will target a browser.
|
||||
It will also have unit tests that should not be included within the built application and that also need additional type information present (`jasmine` in this case).
|
||||
Both parts of the project also share some but not all of the code within the project.
|
||||
As a result, two separate TypeScript configuration files (`tsconfig.app.json` and `tsconfig.spec.json`) are needed to ensure that each part of the application is configured properly and that the right types are used for each part.
|
||||
Also if web workers are used within a project, an additional tsconfig (`tsconfig.worker.json`) is needed.
|
||||
Web workers use similar but incompatible types to the main browser application.
|
||||
This requires the additional configuration file to ensure that the web worker files use the appropriate types and will build successfully.
|
||||
|
||||
While the Angular build system knows about all of these TypeScript configuration files, an IDE using TypeScript's language service does not.
|
||||
Because of this, an IDE will not be able to properly analyze the code from each part of the project and may generate false errors or make suggestions that are incorrect for certain files.
|
||||
By leveraging the new solution-style tsconfig, the IDE can now be aware of the configuration of each part of a project.
|
||||
This allows each file to be treated appropriately based on its tsconfig.
|
||||
IDE features such as error/warning reporting and auto-suggestion will operate more effectively as well.
|
||||
|
||||
The TypeScript 3.9 release [blog post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#solution-style-tsconfig) also contains some additional information regarding this new feature.
|
@ -1,21 +1,20 @@
|
||||
# Solution-style `tsconfig.json` migration
|
||||
# Migrar el estilo de solución `tsconfig.json`
|
||||
|
||||
## What does this migration do?
|
||||
## ¿Qué hace esta migración?
|
||||
|
||||
This migration adds support to existing projects for TypeScript's new ["solution-style" tsconfig feature](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#solution-style-tsconfig).
|
||||
Esta migración agrega soporte a proyectos existentes la nueva funcionalidad de TypeScript ["estilo de solución" tsconfig](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#solution-style-tsconfig).
|
||||
|
||||
Support is added by making two changes:
|
||||
El soporte es agregado al realizar dos cambios:
|
||||
|
||||
1. Renaming the workspace-level `tsconfig.json` to `tsconfig.base.json`.
|
||||
All project [TypeScript configuration files](guide/typescript-configuration) will extend from this base which contains the common options used throughout the workspace.
|
||||
1. Renombrando el espacio de trabajo de `tsconfig.json` a `tsconfig.base.json`. Todos los [archivos de configuración de TypeScript](guide/typescript-configuration) se extenderán desde esta base que contiene las opciones comunes utilizadas en todo el espacio de trabajo.
|
||||
|
||||
2. Adding the solution `tsconfig.json` file at the root of the workspace.
|
||||
This `tsconfig.json` file will only contain references to project-level TypeScript configuration files and is only used by editors/IDEs.
|
||||
2. Agregando el archivo de solución `tsconfig.json` a la raíz del espacio de trabajo. Este archivo `tsconfig.json` solo contendrá referencias a archivos de configuración de TypeScript a nivel de proyecto y solo lo usarán editores/IDEs.
|
||||
|
||||
Como ejemplo, la solución `tsconfig.json` para un nuevo proyecto es la siguiente:
|
||||
|
||||
As an example, the solution `tsconfig.json` for a new project is as follows:
|
||||
```json
|
||||
// This is a "Solution Style" tsconfig.json file, and is used by editors and TypeScript’s language server to improve development experience.
|
||||
// It is not intended to be used to perform a compilation.
|
||||
// Este es un archivo "Estilo de Solución" tsconfig.json, y es usado por editores y servidores del lenguaje TypeScript para mejorar la experiencia de desarrollo.
|
||||
// No está destinado para ser utilizado en la ejecución de una compilación
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
@ -32,24 +31,24 @@ As an example, the solution `tsconfig.json` for a new project is as follows:
|
||||
}
|
||||
```
|
||||
|
||||
## Why is this migration necessary?
|
||||
## ¿Por qué es necesaria esta migración?
|
||||
|
||||
Solution-style `tsconfig.json` files provide an improved editing experience and fix several long-standing defects when editing files in an IDE.
|
||||
IDEs that leverage the TypeScript language service (for example, [Visual Studio Code](https://code.visualstudio.com)), will only use TypeScript configuration files that are named `tsconfig.json`.
|
||||
In complex projects, there may be more than one compilation unit and each of these units may have different settings and options.
|
||||
Los archivos de estilos de solución `tsconfig.json` brindan una experiencia de edición mejorada y corrigen varios defectos antiguos al editar archivos en un IDE.
|
||||
Los IDEs que aprovechan el servicio de lenguaje TypeScript (por ejemplo, [Visual Studio Code](https://code.visualstudio.com)), solo usarán archivos de configuración de TypeScript que se denominan `tsconfig.json`.
|
||||
En proyectos complejos, puede haber más de una unidad de compilación y cada una de estas unidades puede tener diferentes configuraciones y opciones.
|
||||
|
||||
With the Angular CLI, a project will have application code that will target a browser.
|
||||
It will also have unit tests that should not be included within the built application and that also need additional type information present (`jasmine` in this case).
|
||||
Both parts of the project also share some but not all of the code within the project.
|
||||
As a result, two separate TypeScript configuration files (`tsconfig.app.json` and `tsconfig.spec.json`) are needed to ensure that each part of the application is configured properly and that the right types are used for each part.
|
||||
Also if web workers are used within a project, an additional tsconfig (`tsconfig.worker.json`) is needed.
|
||||
Web workers use similar but incompatible types to the main browser application.
|
||||
This requires the additional configuration file to ensure that the web worker files use the appropriate types and will build successfully.
|
||||
Con Angular CLI, un proyecto tendrá un código de la aplicación que tendrá como objetivo un navegador.
|
||||
También tendrá pruebas unitarias que no deben incluirse dentro de la aplicación construida y que también necesitan información adicional presente (`jasmine` en este caso).
|
||||
Ambas partes del proyecto también comparten parte del código dentro del proyecto, pero no todo.
|
||||
Como resultado, se necesitan dos archivos de configuración TypeScript separados (`tsconfig.app.json` y `tsconfig.spec.json`) para garantizar que cada parte de la aplicación esté configurada correctamente y que se usen los tipos correctos para cada parte.
|
||||
Además, si se utilizan web workers dentro de un proyecto, se necesita un tsconfig adicional (`tsconfig.worker.json`).
|
||||
Los web workers utilizan tipos similares pero incompatibles con la aplicación del navegador principal.
|
||||
Esto requiere el archivo de configuración adicional para garantizar que los archivos del web worker utilicen los tipos adecuados y se compilen correctamente.
|
||||
|
||||
While the Angular build system knows about all of these TypeScript configuration files, an IDE using TypeScript's language service does not.
|
||||
Because of this, an IDE will not be able to properly analyze the code from each part of the project and may generate false errors or make suggestions that are incorrect for certain files.
|
||||
By leveraging the new solution-style tsconfig, the IDE can now be aware of the configuration of each part of a project.
|
||||
This allows each file to be treated appropriately based on its tsconfig.
|
||||
IDE features such as error/warning reporting and auto-suggestion will operate more effectively as well.
|
||||
Mientras que el sistema de compilación Angular conoce todos estos archivos de configuración de TypeScript, un IDE que usa el servicio de lenguaje de TypeScript no los conoce.
|
||||
Debido a esto, un IDE no podrá analizar correctamente el código de cada parte del proyecto y puede generar errores falsos o hacer sugerencias incorrectas para ciertos archivos.
|
||||
Al aprovechar el nuevo estilo de solución tsconfig, el IDE ahora puede conocer la configuración de cada parte de un proyecto.
|
||||
Esto permite que cada archivo se trate de forma adecuada basado en su tsconfig.
|
||||
Las funcionalidades del IDE, como informes de error/advertencia y las sugerencias automáticas, también funcionarán de manera más eficaz.
|
||||
|
||||
The TypeScript 3.9 release [blog post](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#solution-style-tsconfig) also contains some additional information regarding this new feature.
|
||||
La [publición en el blog](https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#solution-style-tsconfig) de la versión 3.9 de TypeScript contiene también información adicional sobre esta nueva funcionalidad.
|
||||
|
@ -0,0 +1,33 @@
|
||||
# Update `module` and `target` compiler options migration
|
||||
|
||||
## What does this migration do?
|
||||
|
||||
This migration adjusts the [`target`](https://www.typescriptlang.org/v2/en/tsconfig#target) and [`module`](https://www.typescriptlang.org/v2/en/tsconfig#module) settings within the [TypeScript configuration files](guide/typescript-configuration) for the workspace.
|
||||
The changes to each option vary based on the builder or command that uses the TypeScript configuration file.
|
||||
Unless otherwise noted, changes are only made if the existing value was not changed since the project was created.
|
||||
This process helps ensure that intentional changes to the options are kept in place.
|
||||
|
||||
TypeScript Configuration File(s) | Changed Property | Existing Value | New Value
|
||||
------------- | ------------- | ------------- | ------------- | -------------
|
||||
`<workspace base>/tsconfig.base.json` | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `browser` builder options (`ng build` for applications) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `ng-packgr` builder options (`ng build` for libraries) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `karma` builder options (`ng test` for applications) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `server` builder options (universal) | `"module"` | `"commonjs"` | _removed_
|
||||
Used in `server` builder options (universal) | `"target"` | _any_ | `"es2016"`
|
||||
Used in `protractor` builder options (`ng e2e` for applications) | `"target"` | `"es5"` | `"es2018"`
|
||||
|
||||
## Why is this migration necessary?
|
||||
|
||||
This migration provides improvements to the long-term supportability of projects by updating the projects to use recommended best practice compilation options.
|
||||
|
||||
For the functionality that executes on Node.js, such as Universal and Protractor, the new settings provide performance and troubleshooting benefits as well.
|
||||
The minimum Node.js version for the Angular CLI (v10.13) supports features in ES2018 and earlier.
|
||||
By targeting later ES versions, the compiler transforms less code and can use newer features directly.
|
||||
Since zone.js does not support native `async` and `await`, the universal builds still target ES2016.
|
||||
|
||||
## Why `"es2020"` instead of `"esnext"`?
|
||||
|
||||
In TypeScript 3.9, the behavior of the TypeScript compiler controlled by `module` is the same with both `"esnext"` and `"es2020"` values.
|
||||
This behavior can change in the future, because the `"esnext"` option could evolve in a backwards incompatible ways, resulting in build-time or run-time errors during a TypeScript update.
|
||||
As a result, code can become unstable. Using the `"es2020"` option mitigates this risk.
|
@ -1,33 +1,31 @@
|
||||
# Update `module` and `target` compiler options migration
|
||||
# Actualizar las opciones del compilador `module` y `target` en la migración
|
||||
|
||||
## What does this migration do?
|
||||
## ¿Qué hace esta migración?
|
||||
|
||||
This migration adjusts the [`target`](https://www.typescriptlang.org/v2/en/tsconfig#target) and [`module`](https://www.typescriptlang.org/v2/en/tsconfig#module) settings within the [TypeScript configuration files](guide/typescript-configuration) for the workspace.
|
||||
The changes to each option vary based on the builder or command that uses the TypeScript configuration file.
|
||||
Unless otherwise noted, changes are only made if the existing value was not changed since the project was created.
|
||||
This process helps ensure that intentional changes to the options are kept in place.
|
||||
Esta migración ajusta la configuración de [`target`](https://www.typescriptlang.org/tsconfig#target) y [`module`](https://www.typescriptlang.org/v2/en/tsconfig#module) dentro de [los archivos de configuración de TypeScript](guide/typescript-configuration) para el espacio de trabajo.
|
||||
Los cambios en cada opción varían según el constructor o comando que usa el archivo de configuración de TypeScript. A menos que se indique lo contrario, los cambios solo se realizan si el valor existente no se modificó desde que se creó el proyecto. Este proceso ayuda a garantizar que se mantengan los cambios intencionales en las opciones.
|
||||
|
||||
TypeScript Configuration File(s) | Changed Property | Existing Value | New Value
|
||||
Archivo(s) de configuración de TypeScript | Propiedad Cambiada | Valor existente | Nuevo Valor
|
||||
------------- | ------------- | ------------- | ------------- | -------------
|
||||
`<workspace base>/tsconfig.base.json` | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `browser` builder options (`ng build` for applications) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `ng-packgr` builder options (`ng build` for libraries) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `karma` builder options (`ng test` for applications) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Used in `server` builder options (universal) | `"module"` | `"commonjs"` | _removed_
|
||||
Used in `server` builder options (universal) | `"target"` | _any_ | `"es2016"`
|
||||
Used in `protractor` builder options (`ng e2e` for applications) | `"target"` | `"es5"` | `"es2018"`
|
||||
`<espacio de trabajo>/tsconfig.base.json` | `"module"` | `"esnext"` | `"es2020"`
|
||||
Utilizado en las opciones del constructor de `browser` (`ng build` para aplicaciones) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Utilizado en las opciones del constructor de `ng-packgr` (`ng build` para librerías) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Utilizado en las opciones del constructor de `karma` (`ng test` para aplicaciones) | `"module"` | `"esnext"` | `"es2020"`
|
||||
Utilizado en las opciones (universales) del constructor de `server` | `"module"` | `"commonjs"` | _removed_
|
||||
Utilizado en las opciones (universales) del constructor de `server` | `"target"` | _any_ | `"es2016"`
|
||||
Utilizado en las opciones del constructor de `protractor` (`ng e2e` para aplicaciones) | `"target"` | `"es5"` | `"es2018"`
|
||||
|
||||
## Why is this migration necessary?
|
||||
## ¿Por qué es necesaria esta migración?
|
||||
|
||||
This migration provides improvements to the long-term supportability of projects by updating the projects to use recommended best practice compilation options.
|
||||
Esta migración proporciona mejoras en la compatibilidad a largo plazo de los proyectos mediante la actualización de los proyectos utilizando las buenas prácticas recomendadas en las opciones de compilación.
|
||||
|
||||
For the functionality that executes on Node.js, such as Universal and Protractor, the new settings provide performance and troubleshooting benefits as well.
|
||||
The minimum Node.js version for the Angular CLI (v10.13) supports features in ES2018 and earlier.
|
||||
By targeting later ES versions, the compiler transforms less code and can use newer features directly.
|
||||
Since zone.js does not support native `async` and `await`, the universal builds still target ES2016.
|
||||
Para la funcionalidad que se ejecuta en Node.js, como Universal y Protractor, las nuevas configuraciones también brindan beneficios de rendimiento y resolución de problemas.
|
||||
La versión mínima de Node.js para Angular CLI (v10.13) admite funciones en ES2018 y versiones anteriores.
|
||||
Al apuntar a versiones posteriores de ES, el compilador transforma menos código y puede usar funciones más nuevas directamente.
|
||||
Dado que zone.js no admite `async` y `await` de forma nativa, las compilaciones universales todavía apuntan a ES2016.
|
||||
|
||||
## Why `"es2020"` instead of `"esnext"`?
|
||||
## ¿Por qué `"es2020"` en lugar de `"esnext"`?
|
||||
|
||||
In TypeScript 3.9, the behavior of the TypeScript compiler controlled by `module` is the same with both `"esnext"` and `"es2020"` values.
|
||||
This behavior can change in the future, because the `"esnext"` option could evolve in a backwards incompatible ways, resulting in build-time or run-time errors during a TypeScript update.
|
||||
As a result, code can become unstable. Using the `"es2020"` option mitigates this risk.
|
||||
En TypeScript 3.9, el comportamiento del compilador TypeScript controlado por `module` es el mismo con los valores `"esnext"` y `"es2020"`.
|
||||
Este comportamiento puede cambiar en el futuro, porque la opción `"esnext"` podría evolucionar de manera incompatible hacia atrás, lo que resultaría en errores en tiempo de compilación o de ejecución durante una actualización de TypeScript.
|
||||
Como resultado, el código puede volverse inestable. El uso de la opción `"es2020"` mitiga este riesgo.
|
||||
|
68
aio/content/guide/ngmodules.en.md
Normal file
68
aio/content/guide/ngmodules.en.md
Normal file
@ -0,0 +1,68 @@
|
||||
# NgModules
|
||||
|
||||
**NgModules** configure the injector and the compiler and help organize related things together.
|
||||
|
||||
An NgModule is a class marked by the `@NgModule` decorator.
|
||||
`@NgModule` takes a metadata object that describes how to compile a component's template and how to create an injector at runtime.
|
||||
It identifies the module's own components, directives, and pipes,
|
||||
making some of them public, through the `exports` property, so that external components can use them.
|
||||
`@NgModule` can also add service providers to the application dependency injectors.
|
||||
|
||||
For an example app showcasing all the techniques that NgModules related pages
|
||||
cover, see the <live-example></live-example>. For explanations on the individual techniques, visit the relevant NgModule pages under the NgModules
|
||||
section.
|
||||
|
||||
## Angular modularity
|
||||
|
||||
Modules are a great way to organize an application and extend it with capabilities from external libraries.
|
||||
|
||||
Angular libraries are NgModules, such as `FormsModule`, `HttpClientModule`, and `RouterModule`.
|
||||
Many third-party libraries are available as NgModules such as
|
||||
<a href="https://material.angular.io/">Material Design</a>,
|
||||
<a href="http://ionicframework.com/">Ionic</a>, and
|
||||
<a href="https://github.com/angular/angularfire2">AngularFire2</a>.
|
||||
|
||||
NgModules consolidate components, directives, and pipes into
|
||||
cohesive blocks of functionality, each focused on a
|
||||
feature area, application business domain, workflow, or common collection of utilities.
|
||||
|
||||
Modules can also add services to the application.
|
||||
Such services might be internally developed, like something you'd develop yourself or come from outside sources, such as the Angular router and HTTP client.
|
||||
|
||||
Modules can be loaded eagerly when the application starts or lazy loaded asynchronously by the router.
|
||||
|
||||
NgModule metadata does the following:
|
||||
|
||||
* Declares which components, directives, and pipes belong to the module.
|
||||
* Makes some of those components, directives, and pipes public so that other module's component templates can use them.
|
||||
* Imports other modules with the components, directives, and pipes that components in the current module need.
|
||||
* Provides services that the other application components can use.
|
||||
|
||||
Every Angular app has at least one module, the root module.
|
||||
You [bootstrap](guide/bootstrapping) that module to launch the application.
|
||||
|
||||
The root module is all you need in a simple application with a few components.
|
||||
As the app grows, you refactor the root module into [feature modules](guide/feature-modules)
|
||||
that represent collections of related functionality.
|
||||
You then import these modules into the root module.
|
||||
|
||||
## The basic NgModule
|
||||
|
||||
The [Angular CLI](cli) generates the following basic `AppModule` when creating a new app.
|
||||
|
||||
|
||||
<code-example path="ngmodules/src/app/app.module.1.ts" header="src/app/app.module.ts (default AppModule)">
|
||||
// @NgModule decorator with its metadata
|
||||
</code-example>
|
||||
|
||||
At the top are the import statements. The next section is where you configure the `@NgModule` by stating what components and directives belong to it (`declarations`) as well as which other modules it uses (`imports`). For more information on the structure of an `@NgModule`, be sure to read [Bootstrapping](guide/bootstrapping).
|
||||
|
||||
<hr />
|
||||
|
||||
## More on NgModules
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Feature Modules](guide/feature-modules).
|
||||
* [Entry Components](guide/entry-components).
|
||||
* [Providers](guide/providers).
|
||||
* [Types of NgModules](guide/module-types).
|
@ -1,68 +1,56 @@
|
||||
# NgModules
|
||||
|
||||
**NgModules** configure the injector and the compiler and help organize related things together.
|
||||
**NgModules** configura el inyector y el compilador y ayuda a agrupar cosas similares.
|
||||
|
||||
An NgModule is a class marked by the `@NgModule` decorator.
|
||||
`@NgModule` takes a metadata object that describes how to compile a component's template and how to create an injector at runtime.
|
||||
It identifies the module's own components, directives, and pipes,
|
||||
making some of them public, through the `exports` property, so that external components can use them.
|
||||
`@NgModule` can also add service providers to the application dependency injectors.
|
||||
Un NgModule es una clase marcada por el decorador `@NgModule`. Este toma un objeto metadato que describe cómo compilar la template de un componente, y cómo crear un inyector en tiempo de ejecución.
|
||||
|
||||
For an example app showcasing all the techniques that NgModules related pages
|
||||
cover, see the <live-example></live-example>. For explanations on the individual techniques, visit the relevant NgModule pages under the NgModules
|
||||
section.
|
||||
Identifica los componentes del propio módulo, directivas y pipes, haciendo algunos de ellos públicos (a través de la propiedad `export`) para que los componentes externos puedan utilizarlos.
|
||||
|
||||
## Angular modularity
|
||||
`NgModule` también puede añadir proveedores de servicio a los inyectores de la aplicación de dependencia.
|
||||
|
||||
Modules are a great way to organize an application and extend it with capabilities from external libraries.
|
||||
Para ver una app de ejemplo que contiene todas las técnicas relacionadas con los `NgModules` , consulta <live-example></live-example>. Para explicaciones individuales de cada técnica, visita las páginas específicas bajo la sección NgModules.
|
||||
|
||||
Angular libraries are NgModules, such as `FormsModule`, `HttpClientModule`, and `RouterModule`.
|
||||
Many third-party libraries are available as NgModules such as
|
||||
<a href="https://material.angular.io/">Material Design</a>,
|
||||
<a href="http://ionicframework.com/">Ionic</a>, and
|
||||
<a href="https://github.com/angular/angularfire2">AngularFire2</a>.
|
||||
## Modularidad en Angular
|
||||
|
||||
NgModules consolidate components, directives, and pipes into
|
||||
cohesive blocks of functionality, each focused on a
|
||||
feature area, application business domain, workflow, or common collection of utilities.
|
||||
Los módulos son una muy buena forma de organizar una aplicación y extenderla con funcionalidades de bibliotecas externas.
|
||||
|
||||
Modules can also add services to the application.
|
||||
Such services might be internally developed, like something you'd develop yourself or come from outside sources, such as the Angular router and HTTP client.
|
||||
Las bibliotecas de Angular son NgModules, como `FormsModule`, `HttpClientModule`, and `RouterModule`.
|
||||
|
||||
Modules can be loaded eagerly when the application starts or lazy loaded asynchronously by the router.
|
||||
También hay disponibles bibliotecas de terceros, tales como <a href="https://material.angular.io/">Material Design</a>, <a href="http://ionicframework.com/">Ionic</a>, o <a href="https://github.com/angular/angularfire2">AngularFire2</a>.
|
||||
|
||||
NgModule metadata does the following:
|
||||
Los NgModules consolidan componentes, directivas y pipes en bloques cohesivos de funcionalidades, cada uno centrado en áreas distintas como funciones, aplicación de dominios business, flujo de trabajo, o recolección de utilidades.
|
||||
|
||||
* Declares which components, directives, and pipes belong to the module.
|
||||
* Makes some of those components, directives, and pipes public so that other module's component templates can use them.
|
||||
* Imports other modules with the components, directives, and pipes that components in the current module need.
|
||||
* Provides services that the other application components can use.
|
||||
Los módulos también pueden añadir servicios a la aplicación. Estos servicios pueden haber sido desarrollados internamente, es decir, puedes haberlos desarrollado tú mismo o venir de una fuente extena, como el cliente HTTP y router de Angular.
|
||||
|
||||
Every Angular app has at least one module, the root module.
|
||||
You [bootstrap](guide/bootstrapping) that module to launch the application.
|
||||
Los módulos se pueden cargar de forma *entusiasta*, cuando la aplicación se inicia; o de forma *perezosa*, cargados asíncronamente por el router.
|
||||
|
||||
The root module is all you need in a simple application with a few components.
|
||||
As the app grows, you refactor the root module into [feature modules](guide/feature-modules)
|
||||
that represent collections of related functionality.
|
||||
You then import these modules into the root module.
|
||||
Los metadatos NgModule hacen lo siguiente:
|
||||
|
||||
## The basic NgModule
|
||||
* Declarar qué componentes, directivas y pipes pertenecen al módulo.
|
||||
* Hacer algunos de esos componentes, directivas y pipes públicos para que las templates de los componentes de otros módulos puedan utilizarlos.
|
||||
* Importar otros módulos con los componentes, directivas y pipes que los componentes del módulo actual requieren
|
||||
* Proveer servicios que otros componentes de la aplicación pueden usar.
|
||||
|
||||
The [Angular CLI](cli) generates the following basic `AppModule` when creating a new app.
|
||||
Todas las apps de Angular contienen como mínimo un módulo, el módulo root. Se hace [bootstrap](guide/bootstrapping) a ese módulo para iniciar la aplicación.
|
||||
|
||||
El módulo root es todo lo que necesitas en una aplicación simple de pocos componentes. Según tu app crezca, puedes refactorizar el módulo root en [módulos de funcionalidades](guide/feature-modules), que representan colecciones de funcionalidades similares. Luego, importa esos módulos al módulo root.
|
||||
|
||||
## El NgModule básico
|
||||
|
||||
El [CLI de Angular ](cli) genera los siguientes `AppModule` básicos cuando crea una nueva app.
|
||||
|
||||
<code-example path="ngmodules/src/app/app.module.1.ts" header="src/app/app.module.ts (default AppModule)">
|
||||
// @NgModule decorator with its metadata
|
||||
// decorador @NgModule con sus metadatos
|
||||
</code-example>
|
||||
|
||||
At the top are the import statements. The next section is where you configure the `@NgModule` by stating what components and directives belong to it (`declarations`) as well as which other modules it uses (`imports`). For more information on the structure of an `@NgModule`, be sure to read [Bootstrapping](guide/bootstrapping).
|
||||
Encima están las declaraciones de `import`. La siguiente sección es donde se configura el `@NgModule`, indicando qué componentes y directivas le pertenecen (`declarations`), además de qué otros módulos utiliza (`imports`). Para más información sobre la estructura de un `@NgModule`, consulta [Bootstrapping](guide/bootstrapping).
|
||||
|
||||
<hr />
|
||||
|
||||
## More on NgModules
|
||||
## Más sobre los NgModules
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Feature Modules](guide/feature-modules).
|
||||
* [Entry Components](guide/entry-components).
|
||||
* [Providers](guide/providers).
|
||||
* [Types of NgModules](guide/module-types).
|
||||
Puede que te interesen las siguientes páginas:
|
||||
* [Módulos de funciones](guide/feature-modules).
|
||||
* [Componentes de entrada](guide/entry-components).
|
||||
* [Proveedores](guide/providers).
|
||||
* [Tipos de NgModules](guide/module-types).
|
||||
|
137
aio/content/guide/npm-packages.en.md
Normal file
137
aio/content/guide/npm-packages.en.md
Normal file
@ -0,0 +1,137 @@
|
||||
# Workspace npm dependencies
|
||||
|
||||
The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm packages](https://docs.npmjs.com/getting-started/what-is-npm "What is npm?") and distributed via the [npm registry](https://docs.npmjs.com/).
|
||||
|
||||
You can download and install these npm packages by using the [npm CLI client](https://docs.npmjs.com/cli/install), which is installed with and runs as a [Node.js®](https://nodejs.org "Nodejs.org") application. By default, the Angular CLI uses the npm client.
|
||||
|
||||
Alternatively, you can use the [yarn client](https://yarnpkg.com/) for downloading and installing npm packages.
|
||||
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See [Local Environment Setup](guide/setup-local "Setting up for Local Development") for information about the required versions and installation of `Node.js` and `npm`.
|
||||
|
||||
If you already have projects running on your machine that use other versions of Node.js and npm, consider using [nvm](https://github.com/creationix/nvm) to manage the multiple versions of Node.js and npm.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## `package.json`
|
||||
|
||||
Both `npm` and `yarn` install the packages that are identified in a [`package.json`](https://docs.npmjs.com/files/package.json) file.
|
||||
|
||||
The CLI command `ng new` creates a `package.json` file when it creates the new workspace.
|
||||
This `package.json` is used by all projects in the workspace, including the initial app project that is created by the CLI when it creates the workspace.
|
||||
|
||||
Initially, this `package.json` includes _a starter set of packages_, some of which are required by Angular and others that support common application scenarios.
|
||||
You add packages to `package.json` as your application evolves.
|
||||
You may even remove some.
|
||||
|
||||
The `package.json` is organized into two groups of packages:
|
||||
|
||||
* [Dependencies](guide/npm-packages#dependencies) are essential to *running* applications.
|
||||
* [DevDependencies](guide/npm-packages#dev-dependencies) are only necessary to *develop* applications.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Library developers:** By default, the CLI command [`ng generate library`](cli/generate) creates a `package.json` for the new library. That `package.json` is used when publishing the library to npm.
|
||||
For more information, see the CLI wiki page [Library Support](https://github.com/angular/angular-cli/wiki/stories-create-library).
|
||||
</div>
|
||||
|
||||
|
||||
{@a dependencies}
|
||||
## Dependencies
|
||||
|
||||
The packages listed in the `dependencies` section of `package.json` are essential to *running* applications.
|
||||
|
||||
The `dependencies` section of `package.json` contains:
|
||||
|
||||
* [**Angular packages**](#angular-packages): Angular core and optional modules; their package names begin `@angular/`.
|
||||
|
||||
* [**Support packages**](#support-packages): 3rd party libraries that must be present for Angular apps to run.
|
||||
|
||||
* [**Polyfill packages**](#polyfills): Polyfills plug gaps in a browser's JavaScript implementation.
|
||||
|
||||
To add a new dependency, use the [`ng add`](cli/add) command.
|
||||
|
||||
{@a angular-packages}
|
||||
### Angular packages
|
||||
|
||||
The following Angular packages are included as dependencies in the default `package.json` file for a new Angular workspace.
|
||||
For a complete list of Angular packages, see the [API reference](http://angular.io/api?type=package).
|
||||
|
||||
Package name | Description
|
||||
---------------------------------------- | --------------------------------------------------
|
||||
[**@angular/animations**](api/animations) | Angular's animations library makes it easy to define and apply animation effects such as page and list transitions. For more information, see the [Animations guide](guide/animations).
|
||||
[**@angular/common**](api/common) | The commonly-needed services, pipes, and directives provided by the Angular team. The [`HttpClientModule`](api/common/http/HttpClientModule) is also here, in the [`@angular/common/http`](api/common/http) subfolder. For more information, see the [HttpClient guide](guide/http).
|
||||
**@angular/compiler** | Angular's template compiler. It understands templates and can convert them to code that makes the application run and render. Typically you don’t interact with the compiler directly; rather, you use it indirectly via `platform-browser-dynamic` when JIT compiling in the browser. For more information, see the [Ahead-of-time Compilation guide](guide/aot-compiler).
|
||||
[**@angular/core**](api/core) | Critical runtime parts of the framework that are needed by every application. Includes all metadata decorators, `Component`, `Directive`, dependency injection, and the component lifecycle hooks.
|
||||
[**@angular/forms**](api/forms) | Support for both [template-driven](guide/forms) and [reactive forms](guide/reactive-forms). For information about choosing the best forms approach for your app, see [Introduction to forms](guide/forms-overview).
|
||||
[**@angular/<br />platform‑browser**](api/platform-browser) | Everything DOM and browser related, especially the pieces that help render into the DOM. This package also includes the `bootstrapModuleFactory()` method for bootstrapping applications for production builds that pre-compile with [AOT](guide/aot-compiler).
|
||||
[**@angular/<br />platform‑browser‑dynamic**](api/platform-browser-dynamic) | Includes [providers](api/core/Provider) and methods to compile and run the app on the client using the [JIT compiler](guide/aot-compiler).
|
||||
[**@angular/router**](api/router) | The router module navigates among your app pages when the browser URL changes. For more information, see [Routing and Navigation](guide/router).
|
||||
|
||||
|
||||
{@a support-packages}
|
||||
### Support packages
|
||||
|
||||
The following support packages are included as dependencies in the default `package.json` file for a new Angular workspace.
|
||||
|
||||
|
||||
Package name | Description
|
||||
---------------------------------------- | --------------------------------------------------
|
||||
[**rxjs**](https://github.com/ReactiveX/rxjs) | Many Angular APIs return [_observables_](guide/glossary#observable). RxJS is an implementation of the proposed [Observables specification](https://github.com/tc39/proposal-observable) currently before the [TC39](https://www.ecma-international.org/memento/tc39.htm) committee, which determines standards for the JavaScript language.
|
||||
[**zone.js**](https://github.com/angular/zone.js) | Angular relies on zone.js to run Angular's change detection processes when native JavaScript operations raise events. Zone.js is an implementation of a [specification](https://gist.github.com/mhevery/63fdcdf7c65886051d55) currently before the [TC39](https://www.ecma-international.org/memento/tc39.htm) committee that determines standards for the JavaScript language.
|
||||
|
||||
|
||||
{@a polyfills}
|
||||
### Polyfill packages
|
||||
|
||||
Many browsers lack native support for some features in the latest HTML standards,
|
||||
features that Angular requires.
|
||||
[_Polyfills_](https://en.wikipedia.org/wiki/Polyfill_(programming)) can emulate the missing features.
|
||||
The [Browser Support](guide/browser-support) guide explains which browsers need polyfills and
|
||||
how you can add them.
|
||||
|
||||
|
||||
{@a dev-dependencies}
|
||||
|
||||
## DevDependencies
|
||||
|
||||
The packages listed in the `devDependencies` section of `package.json` help you develop the application on your local machine. You don't deploy them with the production application.
|
||||
|
||||
To add a new `devDependency`, use either one of the following commands:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
npm install --save-dev <package-name>
|
||||
</code-example>
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
yarn add --dev <package-name>
|
||||
</code-example>
|
||||
|
||||
The following `devDependencies` are provided in the default `package.json` file for a new Angular workspace.
|
||||
|
||||
|
||||
Package name | Description
|
||||
---------------------------------------- | -----------------------------------
|
||||
[**@angular‑devkit/<br />build‑angular**](https://github.com/angular/angular-cli/) | The Angular build tools.
|
||||
[**@angular/cli**](https://github.com/angular/angular-cli/) | The Angular CLI tools.
|
||||
**@angular/<br />compiler‑cli** | The Angular compiler, which is invoked by the Angular CLI's `ng build` and `ng serve` commands.
|
||||
**@types/... ** | TypeScript definition files for 3rd party libraries such as Jasmine and Node.js.
|
||||
[**codelyzer**](https://www.npmjs.com/package/codelyzer) | A linter for Angular apps whose rules conform to the Angular [style guide](guide/styleguide).
|
||||
**jasmine/... ** | Packages to support the [Jasmine](https://jasmine.github.io/) test library.
|
||||
**karma/... ** | Packages to support the [karma](https://www.npmjs.com/package/karma) test runner.
|
||||
[**protractor**](https://www.npmjs.com/package/protractor) | An end-to-end (e2e) framework for Angular apps. Built on top of [WebDriverJS](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs).
|
||||
[**ts-node**](https://www.npmjs.com/package/ts-node) | TypeScript execution environment and REPL for Node.js.
|
||||
[**tslint**](https://www.npmjs.com/package/tslint) | A static analysis tool that checks TypeScript code for readability, maintainability, and functionality errors.
|
||||
[**typescript**](https://www.npmjs.com/package/typescript) | The TypeScript language server, including the *tsc* TypeScript compiler.
|
||||
|
||||
|
||||
## Related information
|
||||
|
||||
For information about how the Angular CLI handles packages see the following guides:
|
||||
|
||||
* [Building and serving](guide/build) describes how packages come together to create a development build.
|
||||
* [Deployment](guide/deployment) describes how packages come together to create a production build.
|
||||
|
@ -1,106 +1,104 @@
|
||||
# Workspace npm dependencies
|
||||
# Área de trabajo de las dependencias de npm
|
||||
|
||||
The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm packages](https://docs.npmjs.com/getting-started/what-is-npm "What is npm?") and distributed via the [npm registry](https://docs.npmjs.com/).
|
||||
El framework Angular, el CLI de Angular y los componentes usados por las aplicaciones Angular se empaquetan como [paquetes de npm](https://docs.npmjs.com/getting-started/what-is-npm "¿Qué es npm?") y se distribuyen a través del [registro de npm](https://docs.npmjs.com/).
|
||||
|
||||
You can download and install these npm packages by using the [npm CLI client](https://docs.npmjs.com/cli/install), which is installed with and runs as a [Node.js®](https://nodejs.org "Nodejs.org") application. By default, the Angular CLI uses the npm client.
|
||||
Puedes descargar e instalar esos paquetes de npm utilizando el [cliente CLI de npm](https://docs.npmjs.com/cli/install), el cuál se instala y ejecuta como una aplicación de [Node.js®](https://nodejs.org "Nodejs.org"). Por defecto el CLI de Angular utiliza el cliente de npm.
|
||||
|
||||
Alternatively, you can use the [yarn client](https://yarnpkg.com/) for downloading and installing npm packages.
|
||||
Alternativamente puedes utilizar el [cliente yarn](https://yarnpkg.com/) para descargar e instalar los paquetes de npm.
|
||||
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See [Local Environment Setup](guide/setup-local "Setting up for Local Development") for information about the required versions and installation of `Node.js` and `npm`.
|
||||
Mira [Preparar Entorno Local](guide/setup-local "Preparándose para el desarrollo local") para ver información acerca de la instalación y las versiones requeridas de `Node.js` y `npm`.
|
||||
|
||||
If you already have projects running on your machine that use other versions of Node.js and npm, consider using [nvm](https://github.com/creationix/nvm) to manage the multiple versions of Node.js and npm.
|
||||
Si ya tenías proyectos anteriores en tu máquina que utilizan otras versiones de Node.js y npm considera usar [nvm](https://github.com/creationix/nvm) para gestionar las diferentes versiones de Node.js y npm.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## `package.json`
|
||||
|
||||
Both `npm` and `yarn` install the packages that are identified in a [`package.json`](https://docs.npmjs.com/files/package.json) file.
|
||||
Tanto `npm` como `yarn` instalan los paquetes que están identificados en un archivo [`package.json`](https://docs.npmjs.com/files/package.json).
|
||||
|
||||
The CLI command `ng new` creates a `package.json` file when it creates the new workspace.
|
||||
This `package.json` is used by all projects in the workspace, including the initial app project that is created by the CLI when it creates the workspace.
|
||||
El comando del CLI `ng new` genera un archivo `package.json` al crear el proyecto.
|
||||
Este `package.json` es usado por todos los proyectos en el entorno incluyendo el proyecto inicial generado por el CLI al crear este entorno.
|
||||
|
||||
Initially, this `package.json` includes _a starter set of packages_, some of which are required by Angular and others that support common application scenarios.
|
||||
You add packages to `package.json` as your application evolves.
|
||||
You may even remove some.
|
||||
Inicialmente este `package.json` incluye _una serie de paquetes_, algunos de ellos necesarios para Angular y otros que soportan escenarios comunes de aplicación.
|
||||
Puedes añadir paquetes al `package.json` según tu aplicación crece.
|
||||
También puedes borrarlos si es necesario.
|
||||
|
||||
The `package.json` is organized into two groups of packages:
|
||||
El `package.json` se organiza en dos grupos de paquetes:
|
||||
|
||||
* [Dependencies](guide/npm-packages#dependencies) are essential to *running* applications.
|
||||
* [DevDependencies](guide/npm-packages#dev-dependencies) are only necessary to *develop* applications.
|
||||
* [Dependencies](guide/npm-packages#dependencies) son necesarias para *ejecutar* aplicaciones.
|
||||
* [DevDependencies](guide/npm-packages#dev-dependencies) son solo necesarias para *desarrollar* aplicaciones.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Library developers:** By default, the CLI command [`ng generate library`](cli/generate) creates a `package.json` for the new library. That `package.json` is used when publishing the library to npm.
|
||||
For more information, see the CLI wiki page [Library Support](https://github.com/angular/angular-cli/wiki/stories-create-library).
|
||||
**Desarrolladores de librerías:** Por defecto el comando de CLI [`ng generate library`](cli/generate) crea un `package.json` para la nueva librería. Ese `package.json` es usado cuando se publica la librería en npm.
|
||||
Para más información leer [Creando librerías](guide/creating-libraries).
|
||||
</div>
|
||||
|
||||
|
||||
{@a dependencies}
|
||||
## Dependencies
|
||||
|
||||
The packages listed in the `dependencies` section of `package.json` are essential to *running* applications.
|
||||
Los paquetes listados en la sección `dependencies` del `package.json` son esenciales para *ejecutar* aplicaciones.
|
||||
|
||||
The `dependencies` section of `package.json` contains:
|
||||
La sección `dependencies` del `package.json` contiene:
|
||||
|
||||
* [**Angular packages**](#angular-packages): Angular core and optional modules; their package names begin `@angular/`.
|
||||
* [**Paquetes de Angular**](#angular-packages): El núcleo de Angular y módulos opcionales; el nombre de estos paquetes comienza por `@angular/`.
|
||||
|
||||
* [**Support packages**](#support-packages): 3rd party libraries that must be present for Angular apps to run.
|
||||
* [**Paquetes de soporte**](#support-packages): Librerías de terceros que son necesarias para que las aplicaciones de Angular se puedan ejecutar.
|
||||
|
||||
* [**Polyfill packages**](#polyfills): Polyfills plug gaps in a browser's JavaScript implementation.
|
||||
* [**Paquetes de Polyfill**](#polyfills): Los Polyfills rellenan huecos en la implementación de Javascript de un navegador.
|
||||
|
||||
To add a new dependency, use the [`ng add`](cli/add) command.
|
||||
Para añadir una nueva dependencia usa el comando [`ng add`](cli/add).
|
||||
|
||||
{@a angular-packages}
|
||||
### Angular packages
|
||||
### Paquetes de Angular
|
||||
|
||||
The following Angular packages are included as dependencies in the default `package.json` file for a new Angular workspace.
|
||||
For a complete list of Angular packages, see the [API reference](http://angular.io/api?type=package).
|
||||
Los siguientes paquetes de Angular se incluyen como dependencias en el archivo `package.json` por defecto en un nuevo proyecto de Angular.
|
||||
Para ver la lista completa de paquetes de Angular visita la siguiente [referencia a la API](api?type=package).
|
||||
|
||||
Package name | Description
|
||||
Nombre del Paquete | Descripción
|
||||
---------------------------------------- | --------------------------------------------------
|
||||
[**@angular/animations**](api/animations) | Angular's animations library makes it easy to define and apply animation effects such as page and list transitions. For more information, see the [Animations guide](guide/animations).
|
||||
[**@angular/common**](api/common) | The commonly-needed services, pipes, and directives provided by the Angular team. The [`HttpClientModule`](api/common/http/HttpClientModule) is also here, in the [`@angular/common/http`](api/common/http) subfolder. For more information, see the [HttpClient guide](guide/http).
|
||||
**@angular/compiler** | Angular's template compiler. It understands templates and can convert them to code that makes the application run and render. Typically you don’t interact with the compiler directly; rather, you use it indirectly via `platform-browser-dynamic` when JIT compiling in the browser. For more information, see the [Ahead-of-time Compilation guide](guide/aot-compiler).
|
||||
[**@angular/core**](api/core) | Critical runtime parts of the framework that are needed by every application. Includes all metadata decorators, `Component`, `Directive`, dependency injection, and the component lifecycle hooks.
|
||||
[**@angular/forms**](api/forms) | Support for both [template-driven](guide/forms) and [reactive forms](guide/reactive-forms). For information about choosing the best forms approach for your app, see [Introduction to forms](guide/forms-overview).
|
||||
[**@angular/<br />platform‑browser**](api/platform-browser) | Everything DOM and browser related, especially the pieces that help render into the DOM. This package also includes the `bootstrapModuleFactory()` method for bootstrapping applications for production builds that pre-compile with [AOT](guide/aot-compiler).
|
||||
[**@angular/<br />platform‑browser‑dynamic**](api/platform-browser-dynamic) | Includes [providers](api/core/Provider) and methods to compile and run the app on the client using the [JIT compiler](guide/aot-compiler).
|
||||
[**@angular/router**](api/router) | The router module navigates among your app pages when the browser URL changes. For more information, see [Routing and Navigation](guide/router).
|
||||
[**@angular/animations**](api/animations) | La librería de animaciones de Angular hace sencillo definir y aplicar efectos animados como transiciones de página y listas. Para más información visita [la guía de animaciones](guide/animations).
|
||||
[**@angular/common**](api/common) | Los servicios comunes necesarios, pipes, y directivas proveídas por el equipo de Angular. El [`HttpClientModule`](api/common/http/HttpClientModule) también está aquí, en la subcarpeta [`@angular/common/http`](api/common/http). Para más información visita [la guía de HttpClient](guide/http).
|
||||
**@angular/compiler** | El compilador de plantillas de Angular. Entiende las plantillas y las puede convertir a código que hace que la aplicación se ejecute y renderice. Habitualmente no interactúas con el compilador directamente; más bien lo usas indirectamente a través del `platform-browser-dynamic` cuando se compila en el navegador en tiempo de ejecución (JIT). Para más información visita [la guía de compilación AOT (Ahead-of-time)](guide/aot-compiler).
|
||||
[**@angular/core**](api/core) | Partes críticas del framework requeridas por cualquier aplicación en el tiempo de ejecución. Incluye todos los decoradores de los metadatos, `Componentes`, `Directivas`, inyección de dependencias y los ciclos de vida de los componentes.
|
||||
[**@angular/forms**](api/forms) | Soporte para formularios de tipo [template-driven](guide/forms) y [reactive forms](guide/reactive-forms). Para más información acerca de cuál es la mejor implementación de los formularios para tu aplicación visita [Introducción a los formularios](guide/forms-overview).
|
||||
[**@angular/<br />platform‑browser**](api/platform-browser) | Todo lo relacionado con el DOM y el navegador, especialmente las piezas que ayudan a renderizar el DOM. Este paquete también incluye el método `bootstrapModuleFactory()` para cargar aplicaciones para builds de producción que pre-compilan con [AOT](guide/aot-compiler).
|
||||
[**@angular/<br />platform‑browser‑dynamic**](api/platform-browser-dynamic) | Incluye [providers](api/core/Provider) y métodos para compilar y ejecutar la aplicación en el cliente utilizando el [compilador JIT](guide/aot-compiler).
|
||||
[**@angular/router**](api/router) | El módulo enrutador navega a través de las páginas de tu aplicación cuando la URL cambia. Para más información visita [Enrutado y Navegación](guide/router).
|
||||
|
||||
|
||||
{@a support-packages}
|
||||
### Support packages
|
||||
### Paquetes de soporte
|
||||
|
||||
The following support packages are included as dependencies in the default `package.json` file for a new Angular workspace.
|
||||
Los siguientes paquetes de soporte están incluidos como dependencias en el archivo `package.json` por defecto para un nuevo proyecto de Angular.
|
||||
|
||||
|
||||
Package name | Description
|
||||
Nombre del Paquete | Descripción
|
||||
---------------------------------------- | --------------------------------------------------
|
||||
[**rxjs**](https://github.com/ReactiveX/rxjs) | Many Angular APIs return [_observables_](guide/glossary#observable). RxJS is an implementation of the proposed [Observables specification](https://github.com/tc39/proposal-observable) currently before the [TC39](https://www.ecma-international.org/memento/tc39.htm) committee, which determines standards for the JavaScript language.
|
||||
[**zone.js**](https://github.com/angular/zone.js) | Angular relies on zone.js to run Angular's change detection processes when native JavaScript operations raise events. Zone.js is an implementation of a [specification](https://gist.github.com/mhevery/63fdcdf7c65886051d55) currently before the [TC39](https://www.ecma-international.org/memento/tc39.htm) committee that determines standards for the JavaScript language.
|
||||
[**rxjs**](https://github.com/ReactiveX/rxjs) | Muchas APIs de Angular retornan [_observables_](guide/glossary#observable). RxJS es una implementación de la propuesta actual de [especificación de Observables](https://github.com/tc39/proposal-observable) antes del comité [TC39](https://www.ecma-international.org/memento/tc39.htm) que determina los estándares para el lenguaje JavaScript.
|
||||
[**zone.js**](https://github.com/angular/zone.js) | Angular depende de zone.js para ejecutar el proceso de detección de cambios de Angular cuando operaciones de JavaScript nativas lanzan eventos. Zone.js es una implementación actual de la [especificación](https://gist.github.com/mhevery/63fdcdf7c65886051d55) antes del comité [TC39](https://www.ecma-international.org/memento/tc39.htm) que determina los estándares para el lenguaje JavaScript.
|
||||
|
||||
|
||||
{@a polyfills}
|
||||
### Polyfill packages
|
||||
### Paquetes de Polyfill
|
||||
|
||||
Many browsers lack native support for some features in the latest HTML standards,
|
||||
features that Angular requires.
|
||||
[_Polyfills_](https://en.wikipedia.org/wiki/Polyfill_(programming)) can emulate the missing features.
|
||||
The [Browser Support](guide/browser-support) guide explains which browsers need polyfills and
|
||||
how you can add them.
|
||||
Muchos navegadores no tienen soporte de forma nativa para algunas funcionalidades de los últimos estándares de HTML, funcionalidades que Angular necesita.
|
||||
Los [_Polyfills_](https://en.wikipedia.org/wiki/Polyfill_(programming)) pueden emular las funcionalidades que falten.
|
||||
La guía de [soporte de navegador](guide/browser-support) explica qué navegadores necesitan polyfills y cómo los puedes añadir.
|
||||
|
||||
|
||||
{@a dev-dependencies}
|
||||
|
||||
## DevDependencies
|
||||
|
||||
The packages listed in the `devDependencies` section of `package.json` help you develop the application on your local machine. You don't deploy them with the production application.
|
||||
Los paquetes listados en la sección `devDependencies` del `package.json` te ayudan a desarrollar tu aplicación en tu ordenador. No necesitas desplegarla en un entorno de producción.
|
||||
|
||||
To add a new `devDependency`, use either one of the following commands:
|
||||
Para añadir una `devDependency` usa uno de los siguientes comandos:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
npm install --save-dev <package-name>
|
||||
@ -110,28 +108,28 @@ To add a new `devDependency`, use either one of the following commands:
|
||||
yarn add --dev <package-name>
|
||||
</code-example>
|
||||
|
||||
The following `devDependencies` are provided in the default `package.json` file for a new Angular workspace.
|
||||
Las siguientes `devDependencies` se proveen en el archivo `package.json` por defecto para un nuevo proyeto de Angular.
|
||||
|
||||
|
||||
Package name | Description
|
||||
Nombre del Paquete | Descripción
|
||||
---------------------------------------- | -----------------------------------
|
||||
[**@angular‑devkit/<br />build‑angular**](https://github.com/angular/angular-cli/) | The Angular build tools.
|
||||
[**@angular/cli**](https://github.com/angular/angular-cli/) | The Angular CLI tools.
|
||||
**@angular/<br />compiler‑cli** | The Angular compiler, which is invoked by the Angular CLI's `ng build` and `ng serve` commands.
|
||||
**@types/... ** | TypeScript definition files for 3rd party libraries such as Jasmine and Node.js.
|
||||
[**codelyzer**](https://www.npmjs.com/package/codelyzer) | A linter for Angular apps whose rules conform to the Angular [style guide](guide/styleguide).
|
||||
**jasmine/... ** | Packages to support the [Jasmine](https://jasmine.github.io/) test library.
|
||||
**karma/... ** | Packages to support the [karma](https://www.npmjs.com/package/karma) test runner.
|
||||
[**protractor**](https://www.npmjs.com/package/protractor) | An end-to-end (e2e) framework for Angular apps. Built on top of [WebDriverJS](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs).
|
||||
[**ts-node**](https://www.npmjs.com/package/ts-node) | TypeScript execution environment and REPL for Node.js.
|
||||
[**tslint**](https://www.npmjs.com/package/tslint) | A static analysis tool that checks TypeScript code for readability, maintainability, and functionality errors.
|
||||
[**typescript**](https://www.npmjs.com/package/typescript) | The TypeScript language server, including the *tsc* TypeScript compiler.
|
||||
[**@angular‑devkit/<br />build‑angular**](https://github.com/angular/angular-cli/) | Las herramientas de creación de Angular.
|
||||
[**@angular/cli**](https://github.com/angular/angular-cli/) | Las herramientas del CLI de Angular.
|
||||
**@angular/<br />compiler‑cli** | El compilador de Angular, el cual es invocado por el CLI de Angular mediante los comandos `ng build` y `ng serve`.
|
||||
**@types/... ** | Archivos Typescript de definición de librerías de terceros como Jasmine y Node.js.
|
||||
[**codelyzer**](https://www.npmjs.com/package/codelyzer) | Un linter para las aplicaciones de Angular con las reglas que conforman la [guía de estilos](guide/styleguide) de Angular.
|
||||
**jasmine/... ** | Paquetes para añadir soporte para la librería de testing [Jasmine](https://jasmine.github.io/).
|
||||
**karma/... ** | Paquetes para añadir soporte para el ejecutador de tests [karma](https://www.npmjs.com/package/karma).
|
||||
[**protractor**](https://www.npmjs.com/package/protractor) | Un framework end-to-end (e2e) para aplicaciones de Angular. Construido sobre [WebDriverJS](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs).
|
||||
[**ts-node**](https://www.npmjs.com/package/ts-node) | Entorno de ejecución de Typescript y REPL para Node.js.
|
||||
[**tslint**](https://www.npmjs.com/package/tslint) | Una herramienta de análisis estático de código que comprueba el código Typescript para que sea legible, mantenible y no contenga errores funcionales.
|
||||
[**typescript**](https://www.npmjs.com/package/typescript) | El lenguaje de servidor Typescript, incluye el compilador de Typescript *tsc*.
|
||||
|
||||
|
||||
## Related information
|
||||
## Información relacionada
|
||||
|
||||
For information about how the Angular CLI handles packages see the following guides:
|
||||
Para obtener información acerca de cómo el CLI de Angular maneja los paquetes visita las siguientes guías:
|
||||
|
||||
* [Building and serving](guide/build) describes how packages come together to create a development build.
|
||||
* [Deployment](guide/deployment) describes how packages come together to create a production build.
|
||||
|
||||
* [Creando y sirviendo](guide/build) describe como los paquetes se unen para crear una build de desarrollo.
|
||||
* [Desplegando](guide/deployment) describe como los paquetes se unen para crear una build de producción.
|
||||
|
||||
|
23
aio/content/guide/practical-observable-usage.en.md
Normal file
23
aio/content/guide/practical-observable-usage.en.md
Normal file
@ -0,0 +1,23 @@
|
||||
# Practical observable usage
|
||||
|
||||
Here are some examples of domains in which observables are particularly useful.
|
||||
|
||||
## Type-ahead suggestions
|
||||
|
||||
Observables can simplify the implementation of type-ahead suggestions. Typically, a type-ahead has to do a series of separate tasks:
|
||||
|
||||
* Listen for data from an input.
|
||||
* Trim the value (remove whitespace) and make sure it’s a minimum length.
|
||||
* Debounce (so as not to send off API requests for every keystroke, but instead wait for a break in keystrokes).
|
||||
* Don’t send a request if the value stays the same (rapidly hit a character, then backspace, for instance).
|
||||
* Cancel ongoing AJAX requests if their results will be invalidated by the updated results.
|
||||
|
||||
Writing this in full JavaScript can be quite involved. With observables, you can use a simple series of RxJS operators:
|
||||
|
||||
<code-example path="practical-observable-usage/src/typeahead.ts" header="Typeahead"></code-example>
|
||||
|
||||
## Exponential backoff
|
||||
|
||||
Exponential backoff is a technique in which you retry an API after failure, making the time in between retries longer after each consecutive failure, with a maximum number of retries after which the request is considered to have failed. This can be quite complex to implement with promises and other methods of tracking AJAX calls. With observables, it is very easy:
|
||||
|
||||
<code-example path="practical-observable-usage/src/backoff.ts" header="Exponential backoff"></code-example>
|
@ -1,23 +1,23 @@
|
||||
# Practical observable usage
|
||||
|
||||
Here are some examples of domains in which observables are particularly useful.
|
||||
Aquí tienes algunos ejemplos de dominios en los que las observables son particularmente útiles.
|
||||
|
||||
## Type-ahead suggestions
|
||||
## Sugerencias de autocompletado
|
||||
|
||||
Observables can simplify the implementation of type-ahead suggestions. Typically, a type-ahead has to do a series of separate tasks:
|
||||
Las observables pueden simplificar la implementación de las sugerencias del autocompletado. Normalmente, un autocompletado realiza una serie de tareas:
|
||||
|
||||
* Listen for data from an input.
|
||||
* Trim the value (remove whitespace) and make sure it’s a minimum length.
|
||||
* Debounce (so as not to send off API requests for every keystroke, but instead wait for a break in keystrokes).
|
||||
* Don’t send a request if the value stays the same (rapidly hit a character, then backspace, for instance).
|
||||
* Cancel ongoing AJAX requests if their results will be invalidated by the updated results.
|
||||
* Recibe la información desde una entrada.
|
||||
* Recorta el valor (eliminando espacios) y se asegura de que tiene una longitud mínima.
|
||||
* Hacer debounce (no manda solicitudes a la API por cada tecla pulsada, sino que espera una parada entre letras).
|
||||
* No se manda una solicitud si el valor es el mismo (por ejemplo, teclear un caracter y, al momento, borrarlo)
|
||||
* Cancelar solicitudes AJAX activas si sus resultados van a ser invalidados por los resultados actualizados siguientes.
|
||||
|
||||
Writing this in full JavaScript can be quite involved. With observables, you can use a simple series of RxJS operators:
|
||||
Escribir esto íntegramente en JavaScript puede ser bastante tedioso. Con las observables, puedes utilizar una serie de simples operadores RxJS:
|
||||
|
||||
<code-example path="practical-observable-usage/src/typeahead.ts" header="Typeahead"></code-example>
|
||||
|
||||
## Exponential backoff
|
||||
## Retroceso exponencial
|
||||
|
||||
Exponential backoff is a technique in which you retry an API after failure, making the time in between retries longer after each consecutive failure, with a maximum number of retries after which the request is considered to have failed. This can be quite complex to implement with promises and other methods of tracking AJAX calls. With observables, it is very easy:
|
||||
El retroceso exponencial es una técnica en la cual vuelves a intentar la API después de un fracaso, haciendo que el tiempo entre intentos tras cada fracaso consecutivo sea cada vez más largo, con un número máximo de intentos hasta que consideras que la solicitud ha sido fallida. Esto puede ser bastante complejo de implementar con promesas y otros métodos de tracking que AJAX emplea. Con observables, es muy fácil:
|
||||
|
||||
<code-example path="practical-observable-usage/src/backoff.ts" header="Exponential backoff"></code-example>
|
||||
|
93
aio/content/guide/roadmap.en.md
Normal file
93
aio/content/guide/roadmap.en.md
Normal file
@ -0,0 +1,93 @@
|
||||
# Angular Roadmap
|
||||
|
||||
Angular receives a large number of feature requests, both from inside Google and from the broader open-source community. At the same time, our list of projects contains plenty of maintenance tasks, code refactorings, potential performance improvements, and so on. We bring together representatives from developer relations, product management, and engineering to prioritize this list. As new projects come into the queue, we regularly position them based on relative priority to other projects. As work gets done, projects will move up in the queue.
|
||||
|
||||
The projects below are not associated with a particular Angular version. We'll release them on completion, and they will be part of a specific version based on our release schedule, following semantic versioning. For example, features are released in the next minor after they are complete, or the next major if they include breaking changes.
|
||||
|
||||
## In Progress
|
||||
|
||||
### Operation Bye Bye Backlog (aka Operation Byelog)
|
||||
|
||||
We are actively investing up to 50% of our engineering capacity on triaging issues and PRs until we have a clear understanding of broader community needs. After that, we'll commit up to 20% of our engineering capacity to keep up with new submissions promptly.
|
||||
|
||||
### Support TypeScript 4.0
|
||||
|
||||
We're working on adding support for TypeScript 4.0 ahead of its stable release. We always want Angular to stay up-to-date with the latest version of TypeScript so that developers get the best the language has to offer.
|
||||
|
||||
### Update our e2e testing strategy
|
||||
|
||||
To ensure we provide a future-proof e2e testing strategy, we want to evaluate the state of Protractor, community innovations, e2e best practices, and explore novel opportunities.
|
||||
|
||||
### Angular libraries use Ivy
|
||||
|
||||
We are investing in the design and development of Ivy library distribution plan, which will include an update of the library package format to use Ivy compilation, unblock the deprecation of the View Engine library format, and [ngcc](guide/glossary#ngcc).
|
||||
|
||||
### Evaluate future RxJS changes (v7 and beyond)
|
||||
|
||||
We want to ensure Angular developers are taking advantage of the latest capabilities of RxJS and have a smooth transition to the next major releases of the framework. For this purpose, we will explore and document the scope of the changes in v7 and beyond of RxJS and plan an update strategy.
|
||||
|
||||
### Angular language service uses Ivy
|
||||
|
||||
Today the language service still uses the View Engine compiler and type checking, even for Ivy applications. We want to use the Ivy template parser and improved type checking for the Angular Language service to match application behavior. This migration will also be a step towards unblocking the removal of View Engine, which will simplify Angular, reduce the npm package size, and improve the framework's maintainability.
|
||||
|
||||
### Expand component harnesses best practices
|
||||
|
||||
Angular CDK introduced the concept of [component test harnesses](https://material.angular.io/cdk/test-harnesses) to Angular in version 9. Test harnesses allow component authors to create supported APIs for testing component interactions. We're continuing to improve this harness infrastructure and clarifying the best practices around using harnesses. We're also working to drive more harness adoption inside of Google.
|
||||
|
||||
### Support native [Trusted Types](https://web.dev/trusted-types/) in Angular
|
||||
|
||||
In collaboration with Google's security team, we're adding support for the new Trusted Types API. This web platform API will help developers build more secure web applications.
|
||||
|
||||
### Integrate [MDC Web](https://material.io/develop/web/) into Angular Material
|
||||
|
||||
MDC Web is a library created by Google's Material Design team that provides reusable primitives for building Material Design components. The Angular team is incorporating these primitives into Angular Material. Using MDC Web will align Angular Material more closely with the Material Design specification, expand accessibility, overall improve component quality, and improve our team's velocity.
|
||||
|
||||
### Offer Google engineers better integration with Angular and Google's internal server stack
|
||||
|
||||
This is an internal project to add support for Angular front-ends to Google's internal integrated server stack.
|
||||
|
||||
### Angular versioning & branching
|
||||
|
||||
We want to consolidate release management tooling between Angular's multiple GitHub repositories ([angular/angular](https://github.com/angular/angular), [angular/angular-cli](https://github.com/angular/angular-cli), and [angular/components](https://github.com/angular/components)). This effort will allow us to reuse infrastructure, unify and simplify processes, and improve our release process's reliability.
|
||||
|
||||
## Future
|
||||
|
||||
### Refresh introductory documentation
|
||||
|
||||
We will redefine the user learning journeys and refresh the introductory documentation. We will clearly state the benefits of Angular, how to explore its capabilities, and provide guidance so developers can become proficient with the framework in as little time as possible.
|
||||
|
||||
### Strict typing for `@angular/forms`
|
||||
|
||||
We will work on implementing stricter type checking for reactive forms. This way, we will allow developers to catch more issues during development time, enable better text editor and IDE support, and improve the type checking for reactive forms.
|
||||
|
||||
### webpack 5 in the Angular CLI
|
||||
|
||||
Webpack 5 brings a lot of build speed and bundle size improvements. To make them available for Angular developers, we will invest in migrating Angular CLI from using deprecated and removed webpack APIs.
|
||||
|
||||
### Commit message standardization
|
||||
|
||||
We want to unify commit message requirements and conformance across Angular repositories ([angular/angular](https://github.com/angular/angular), [angular/components](https://github.com/angular/components), [angular/angular-cli](https://github.com/angular/angular-cli)) to bring consistency to our development process and reuse infrastructure tooling.
|
||||
|
||||
### Optional Zone.js
|
||||
|
||||
We are going to design and implement a plan to make Zone.js optional from Angular applications. This way, we will simplify the framework, improve debugging, and reduce application bundle size. Additionally, this will allow us to take advantage of native async/await syntax, which currently Zone.js does not support.
|
||||
|
||||
### Remove legacy [View Engine](guide/ivy)
|
||||
|
||||
After the transition of all our internal tooling to Ivy has completed, we want to remove the legacy View Engine for smaller Angular conceptual overhead, smaller package size, lower maintenance cost, and lower complexity of the codebase.
|
||||
|
||||
### Angular DevTools
|
||||
|
||||
We’ll be working on development tooling for Angular that will provide utilities for debugging and performance profiling. This project aims to help developers understand the component structure and the change detection in an Angular application.
|
||||
|
||||
### Optional NgModules
|
||||
|
||||
To simplify the Angular mental model and learning journey, we’ll be working on making NgModules optional. This work will allow developers to develop standalone components and implement an alternative API for declaring the component’s compilation scope.
|
||||
|
||||
### Ergonomic component level code-splitting APIs
|
||||
|
||||
A common problem of web applications is their slow initial load time. A way to improve it is to apply more granular code-splitting on a component level. To encourage this practice, we’ll be working on more ergonomic code-splitting APIs.
|
||||
|
||||
### Migration to ESLint
|
||||
|
||||
With the deprecation of TSLint we will be moving to ESLint. As part of the process, we will work on ensuring backward compatibility with our current recommended TSLint configuration, implement a migration strategy for existing Angular applications and introduce new tooling to the Angular CLI toolchain.
|
@ -1,93 +1,93 @@
|
||||
# Angular Roadmap
|
||||
# Hoja de ruta Angular
|
||||
|
||||
Angular receives a large number of feature requests, both from inside Google and from the broader open-source community. At the same time, our list of projects contains plenty of maintenance tasks, code refactorings, potential performance improvements, and so on. We bring together representatives from developer relations, product management, and engineering to prioritize this list. As new projects come into the queue, we regularly position them based on relative priority to other projects. As work gets done, projects will move up in the queue.
|
||||
Angular recibe una gran cantidad de solicitudes de fucionalidades, tanto desde dentro de Google como desde la comunidad de código abierto en general. Al mismo tiempo, nuestra lista de proyectos contiene muchas tareas de mantenimiento, refactorizaciones de código, posibles mejoras de rendimiento, etc. Reunimos a representantes de relaciones con desarrolladores, gestión de productos e ingeniería para priorizar esta lista. A medida que nuevos proyectos entran en la cola, los posicionamos regularmente en función de la prioridad relativa a otros proyectos. A medida que se realiza el trabajo, los proyectos avanzarán en la cola.
|
||||
|
||||
The projects below are not associated with a particular Angular version. We'll release them on completion, and they will be part of a specific version based on our release schedule, following semantic versioning. For example, features are released in the next minor after they are complete, or the next major if they include breaking changes.
|
||||
Los proyectos a continuación no están asociados con una versión de Angular en particular. Los publicaremos una vez finalizados, y serán parte de una versión específica basada en nuestro calendario de lanzamientos, siguiendo el control de versiones semántico. Por ejemplo, las funciones se publican en el siguiente menor después de que se completan, o el siguiente mayor si incluyen cambios importantes.
|
||||
|
||||
## In Progress
|
||||
## En progreso
|
||||
|
||||
### Operation Bye Bye Backlog (aka Operation Byelog)
|
||||
### Operación Bye Bye Backlog (también conocida como Operación Byelog)
|
||||
|
||||
We are actively investing up to 50% of our engineering capacity on triaging issues and PRs until we have a clear understanding of broader community needs. After that, we'll commit up to 20% of our engineering capacity to keep up with new submissions promptly.
|
||||
Estamos invirtiendo activamente hasta el 50% de nuestra capacidad de ingeniería para clasificación de _issues_ y PRs hasta que tengamos una comprensión clara de las necesidades de la comunidad en general. Después de eso, comprometeremos hasta el 20% de nuestra capacidad de ingeniería para mantenernos al día con los nuevos envíos de _issues_ y PRs rápidamente.
|
||||
|
||||
### Support TypeScript 4.0
|
||||
### Soporte a TypeScript 4.0
|
||||
|
||||
We're working on adding support for TypeScript 4.0 ahead of its stable release. We always want Angular to stay up-to-date with the latest version of TypeScript so that developers get the best the language has to offer.
|
||||
Estamos trabajando para agregar soporte para TypeScript 4.0 antes de su versión estable. Siempre queremos que Angular se mantenga actualizado con la última versión de TypeScript para que los desarrolladores obtengan lo mejor que el lenguaje tiene para ofrecer.
|
||||
|
||||
### Update our e2e testing strategy
|
||||
### Actualizar nuestra estrategia de pruebas e2e
|
||||
|
||||
To ensure we provide a future-proof e2e testing strategy, we want to evaluate the state of Protractor, community innovations, e2e best practices, and explore novel opportunities.
|
||||
Para garantizar que proporcionamos una estrategia de prueba de e2e preparada para el futuro, queremos evaluar el estado de Protractor, las innovaciones de la comunidad, las mejores prácticas de e2e y explorar nuevas oportunidades.
|
||||
|
||||
### Angular libraries use Ivy
|
||||
### Las librerías de Angular usan Ivy
|
||||
|
||||
We are investing in the design and development of Ivy library distribution plan, which will include an update of the library package format to use Ivy compilation, unblock the deprecation of the View Engine library format, and [ngcc](guide/glossary#ngcc).
|
||||
Estamos invirtiendo en el diseño y desarrollo del plan de distribución de la librería Ivy, que incluirá una actualización del formato del paquete de la librería para usar la compilación de Ivy, desbloquear la obsolescencia del formato de la librería View Engine y [ngcc](guide/glossary#ngcc).
|
||||
|
||||
### Evaluate future RxJS changes (v7 and beyond)
|
||||
### Evaluar los cambios futuros de RxJS (v7 y posteriores)
|
||||
|
||||
We want to ensure Angular developers are taking advantage of the latest capabilities of RxJS and have a smooth transition to the next major releases of the framework. For this purpose, we will explore and document the scope of the changes in v7 and beyond of RxJS and plan an update strategy.
|
||||
Queremos asegurarnos de que los desarrolladores Angular aprovechen las últimas capacidades de RxJS y tengan una transición sin problemas a las próximas versiones principales del framework. Para este propósito, exploraremos y documentaremos el alcance de los cambios en la versión 7 y posteriores de RxJS y planificaremos una estrategia de actualización.
|
||||
|
||||
### Angular language service uses Ivy
|
||||
### El servicio de lenguaje Angular usa Ivy
|
||||
|
||||
Today the language service still uses the View Engine compiler and type checking, even for Ivy applications. We want to use the Ivy template parser and improved type checking for the Angular Language service to match application behavior. This migration will also be a step towards unblocking the removal of View Engine, which will simplify Angular, reduce the npm package size, and improve the framework's maintainability.
|
||||
Hoy en día, el servicio de lenguaje todavía utiliza el compilador de View Engine y la verificación de tipos, incluso para aplicaciones Ivy. Queremos utilizar el analizador de plantillas Ivy y la verificación de tipos mejorada para que el servicio Angular Language coincida con el comportamiento de la aplicación. Esta migración también será un paso hacia el desbloqueo de la eliminación de View Engine, que simplificará Angular, reducirá el tamaño del paquete npm y mejorará la capacidad de mantenimiento del marco.
|
||||
|
||||
### Expand component harnesses best practices
|
||||
### Ampliar las buenas prácticas en componentes harnesses
|
||||
|
||||
Angular CDK introduced the concept of [component test harnesses](https://material.angular.io/cdk/test-harnesses) to Angular in version 9. Test harnesses allow component authors to create supported APIs for testing component interactions. We're continuing to improve this harness infrastructure and clarifying the best practices around using harnesses. We're also working to drive more harness adoption inside of Google.
|
||||
Angular CDK introdujo el concepto de [component test harnesses](https://material.angular.io/cdk/test-harnesses) en Angular en la versión 9. Los harnesses de prueba permiten a los autores de componentes crear API compatibles para probar interacciones de componentes. Continuamos mejorando esta infraestructura de harness y aclarando las mejores prácticas en torno al uso de harnesses. También estamos trabajando para impulsar una mayor adopción de harness dentro de Google.
|
||||
|
||||
### Support native [Trusted Types](https://web.dev/trusted-types/) in Angular
|
||||
### Soporte nativo de [Trusted Types](https://web.dev/trusted-types/) en Angular
|
||||
|
||||
In collaboration with Google's security team, we're adding support for the new Trusted Types API. This web platform API will help developers build more secure web applications.
|
||||
En colaboración con el equipo de seguridad de Google, estamos agregando soporte para la nueva API Trusted Types. Esta API de plataforma web ayudará a los desarrolladores a crear aplicaciones web más seguras.
|
||||
|
||||
### Integrate [MDC Web](https://material.io/develop/web/) into Angular Material
|
||||
### Integrar [MDC Web](https://material.io/develop/web/) en Angular Material
|
||||
|
||||
MDC Web is a library created by Google's Material Design team that provides reusable primitives for building Material Design components. The Angular team is incorporating these primitives into Angular Material. Using MDC Web will align Angular Material more closely with the Material Design specification, expand accessibility, overall improve component quality, and improve our team's velocity.
|
||||
MDC Web es una librería creada por el equipo de Material Design de Google que proporciona primitivas reutilizables para construir componentes de Material Design. El equipo de Angular está incorporando estas primitivas en Angular Material. El uso de MDC Web alineará Angular Material más estrechamente con la especificación de Material Design, expandirá la accesibilidad, mejorará en general la calidad de los componentes y mejorará la velocidad de nuestro equipo.
|
||||
|
||||
### Offer Google engineers better integration with Angular and Google's internal server stack
|
||||
### Ofrecer a los ingenieros de Google una mejor integración con Angular y la pila de servidores internos de Google
|
||||
|
||||
This is an internal project to add support for Angular front-ends to Google's internal integrated server stack.
|
||||
Este es un proyecto interno para agregar soporte para interfaces Angular a la pila de servidores integrados internos de Google.
|
||||
|
||||
### Angular versioning & branching
|
||||
### Control de versiones y ramificación Angular
|
||||
|
||||
We want to consolidate release management tooling between Angular's multiple GitHub repositories ([angular/angular](https://github.com/angular/angular), [angular/angular-cli](https://github.com/angular/angular-cli), and [angular/components](https://github.com/angular/components)). This effort will allow us to reuse infrastructure, unify and simplify processes, and improve our release process's reliability.
|
||||
Queremos consolidar las herramientas de administración de versiones entre los múltiples repositorios de GitHub de Angular ([angular/angular](https://github.com/angular/angular), [angular/angular-cli](https://github.com/angular/angular-cli), y [angular/components](https://github.com/angular/components)). Este esfuerzo nos permitirá reutilizar la infraestructura, unificar y simplificar procesos y mejorar la confiabilidad de nuestro proceso de lanzamiento.
|
||||
|
||||
## Future
|
||||
## Futuro
|
||||
|
||||
### Refresh introductory documentation
|
||||
### Actualizar la documentación introductoria
|
||||
|
||||
We will redefine the user learning journeys and refresh the introductory documentation. We will clearly state the benefits of Angular, how to explore its capabilities, and provide guidance so developers can become proficient with the framework in as little time as possible.
|
||||
Redefiniremos las rutas de aprendizaje del usuario y actualizaremos la documentación introductoria. Expresaremos claramente los beneficios de Angular, cómo explorar sus capacidades y brindaremos orientación para que los desarrolladores puedan dominar el framework en el menor tiempo posible.
|
||||
|
||||
### Strict typing for `@angular/forms`
|
||||
### Tipos de datos estrictos para `@angular/forms`
|
||||
|
||||
We will work on implementing stricter type checking for reactive forms. This way, we will allow developers to catch more issues during development time, enable better text editor and IDE support, and improve the type checking for reactive forms.
|
||||
Trabajaremos en la implementación de una verificación de tipo más estricta para los formularios reactivos. De esta manera, permitiremos a los desarrolladores detectar más problemas durante el tiempo de desarrollo, habilitar un mejor editor de texto y soporte IDE, y mejorar la verificación de tipos para formularios reactivos.
|
||||
|
||||
### webpack 5 in the Angular CLI
|
||||
### webpack 5 en Angular CLI
|
||||
|
||||
Webpack 5 brings a lot of build speed and bundle size improvements. To make them available for Angular developers, we will invest in migrating Angular CLI from using deprecated and removed webpack APIs.
|
||||
Webpack 5 trae muchas mejoras en la velocidad de compilación y el tamaño del paquete. Para que estén disponibles para los desarrolladores de Angular, invertiremos en migrar la CLI de Angular del uso de API de paquetes web obsoletos y eliminados.
|
||||
|
||||
### Commit message standardization
|
||||
### Estandarización del mensaje del commit
|
||||
|
||||
We want to unify commit message requirements and conformance across Angular repositories ([angular/angular](https://github.com/angular/angular), [angular/components](https://github.com/angular/components), [angular/angular-cli](https://github.com/angular/angular-cli)) to bring consistency to our development process and reuse infrastructure tooling.
|
||||
Queremos unificar los requisitos y la conformidad de los commit messages en los repositorios Angular ([angular/angular](https://github.com/angular/angular), [angular/components](https://github.com/angular/components), [angular/angular-cli](https://github.com/angular/angular-cli)) ara brindar coherencia a nuestro proceso de desarrollo y reutilizar las herramientas de infraestructura.
|
||||
|
||||
### Optional Zone.js
|
||||
### Zone.js opcional
|
||||
|
||||
We are going to design and implement a plan to make Zone.js optional from Angular applications. This way, we will simplify the framework, improve debugging, and reduce application bundle size. Additionally, this will allow us to take advantage of native async/await syntax, which currently Zone.js does not support.
|
||||
Vamos a diseñar e implementar un plan para que Zone.js sea opcional desde las aplicaciones Angular. De esta forma, simplificaremos el framework, mejoraremos la depuración y reduciremos el tamaño del paquete de aplicaciones. Además, esto nos permitirá aprovechar la sintaxis nativa async/await, que actualmente Zone.js no admite.
|
||||
|
||||
### Remove legacy [View Engine](guide/ivy)
|
||||
### Eliminar legacy [View Engine](guide/ivy)
|
||||
|
||||
After the transition of all our internal tooling to Ivy has completed, we want to remove the legacy View Engine for smaller Angular conceptual overhead, smaller package size, lower maintenance cost, and lower complexity of the codebase.
|
||||
Una vez que se haya completado la transición de todas nuestras herramientas internas a Ivy, queremos eliminar el legacy View Engine para una sobrecarga conceptual Angular más pequeña, un tamaño de paquete más pequeño, un costo de mantenimiento más bajo y una menor complejidad del código base.
|
||||
|
||||
### Angular DevTools
|
||||
### Herramientas de desarrollo Angular
|
||||
|
||||
We’ll be working on development tooling for Angular that will provide utilities for debugging and performance profiling. This project aims to help developers understand the component structure and the change detection in an Angular application.
|
||||
Trabajaremos en herramientas de desarrollo para Angular que proporcionarán utilidades para depuración y generación de perfiles de rendimiento. Este proyecto tiene como objetivo ayudar a los desarrolladores a comprender la estructura del componente y la detección de cambios en una aplicación Angular.
|
||||
|
||||
### Optional NgModules
|
||||
### NgModules opcionales
|
||||
|
||||
To simplify the Angular mental model and learning journey, we’ll be working on making NgModules optional. This work will allow developers to develop standalone components and implement an alternative API for declaring the component’s compilation scope.
|
||||
Para simplificar el modelo mental Angular y la ruta de aprendizaje, trabajaremos para hacer que NgModules sea opcional. Este trabajo permitirá a los desarrolladores desarrollar componentes independientes e implementar una API alternativa para declarar el alcance de compilación del componente.
|
||||
|
||||
### Ergonomic component level code-splitting APIs
|
||||
### API de división de código a nivel de componente ergonómico
|
||||
|
||||
A common problem of web applications is their slow initial load time. A way to improve it is to apply more granular code-splitting on a component level. To encourage this practice, we’ll be working on more ergonomic code-splitting APIs.
|
||||
Un problema común de las aplicaciones web es su lento tiempo de carga inicial. Una forma de mejorarlo es aplicar una división de código más granular a nivel de componente. Para fomentar esta práctica, trabajaremos en API de división de código más ergonómicas.
|
||||
|
||||
### Migration to ESLint
|
||||
### Migración a ESLint
|
||||
|
||||
With the deprecation of TSLint we will be moving to ESLint. As part of the process, we will work on ensuring backward compatibility with our current recommended TSLint configuration, implement a migration strategy for existing Angular applications and introduce new tooling to the Angular CLI toolchain.
|
||||
Con la deprecación de TSLint, nos trasladaremos a ESLint. Como parte del proceso, trabajaremos para garantizar la compatibilidad con versiones anteriores de nuestra configuración TSLint recomendada actual, implementaremos una estrategia de migración para las aplicaciones Angular existentes e introduciremos nuevas herramientas en la cadena de herramientas Angular CLI.
|
||||
|
132
aio/content/guide/route-animations.en.md
Normal file
132
aio/content/guide/route-animations.en.md
Normal file
@ -0,0 +1,132 @@
|
||||
# Route transition animations
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
A basic understanding of the following concepts:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
* [Reusable animations](guide/reusable-animations)
|
||||
|
||||
<hr>
|
||||
|
||||
Routing enables users to navigate between different routes in an application. When a user navigates from one route to another, the Angular router maps the URL path to a relevant component and displays its view. Animating this route transition can greatly enhance the user experience.
|
||||
|
||||
The Angular router comes with high-level animation functions that let you animate the transitions between views when a route changes. To produce an animation sequence when switching between routes, you need to define nested animation sequences. Start with the top-level component that hosts the view, and nest additional animations in the components that host the embedded views.
|
||||
|
||||
To enable routing transition animation, do the following:
|
||||
|
||||
1. Import the routing module into the application and create a routing configuration that defines the possible routes.
|
||||
2. Add a router outlet to tell the Angular router where to place the activated components in the DOM.
|
||||
3. Define the animation.
|
||||
|
||||
|
||||
Let's illustrate a router transition animation by navigating between two routes, *Home* and *About* associated with the `HomeComponent` and `AboutComponent` views respectively. Both of these component views are children of the top-most view, hosted by `AppComponent`. We'll implement a router transition animation that slides in the new view to the right and slides out the old view when the user navigates between the two routes.
|
||||
|
||||
</br>
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/animations/route-animation.gif" alt="Animations in action" width="440">
|
||||
</div>
|
||||
|
||||
## Route configuration
|
||||
|
||||
To begin, configure a set of routes using methods available in the `RouterModule` class. This route configuration tells the router how to navigate.
|
||||
|
||||
Use the `RouterModule.forRoot` method to define a set of routes. Also, import this `RouterModule` to the `imports` array of the main module, `AppModule`.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** Use the `RouterModule.forRoot` method in the root module, `AppModule`, to register top-level application routes and providers. For feature modules, call the `RouterModule.forChild` method to register additional routes.
|
||||
|
||||
</div>
|
||||
|
||||
The following configuration defines the possible routes for the application.
|
||||
|
||||
<code-example path="animations/src/app/app.module.ts" header="src/app/app.module.ts" region="route-animation-data" language="typescript"></code-example>
|
||||
|
||||
The `home` and `about` paths are associated with the `HomeComponent` and `AboutComponent` views. The route configuration tells the Angular router to instantiate the `HomeComponent` and `AboutComponent` views when the navigation matches the corresponding path.
|
||||
|
||||
In addition to `path` and `component`, the `data` property of each route defines the key animation-specific configuration associated with a route. The `data` property value is passed into `AppComponent` when the route changes. You can also pass additional data in route config that is consumed within the animation. The data property value has to match the transitions defined in the `routeAnimation` trigger, which we'll define later.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The `data` property names that you use can be arbitrary. For example, the name *animation* used in the example above is an arbitrary choice.
|
||||
|
||||
</div>
|
||||
|
||||
## Router outlet
|
||||
|
||||
After configuring the routes, tell the Angular router where to render the views when matched with a route. You can set a router outlet by inserting a `<router-outlet>` container inside the root `AppComponent` template.
|
||||
|
||||
The `<router-outlet>` container has an attribute directive that contains data about active routes and their states, based on the `data` property that we set in the route configuration.
|
||||
|
||||
<code-example path="animations/src/app/app.component.html" header="src/app/app.component.html" region="route-animations-outlet"></code-example>
|
||||
|
||||
`AppComponent` defines a method that can detect when a view changes. The method assigns an animation state value to the animation trigger (`@routeAnimation`) based on the route configuration `data` property value. Here's an example of an `AppComponent` method that detects when a route change happens.
|
||||
|
||||
<code-example path="animations/src/app/app.component.ts" header="src/app/app.component.ts" region="prepare-router-outlet" language="typescript"></code-example>
|
||||
|
||||
Here, the `prepareRoute()` method takes the value of the outlet directive (established through `#outlet="outlet"`) and returns a string value representing the state of the animation based on the custom data of the current active route. You can use this data to control which transition to execute for each route.
|
||||
|
||||
## Animation definition
|
||||
|
||||
Animations can be defined directly inside your components. For this example we are defining the animations in a separate file, which allows us to re-use the animations.
|
||||
|
||||
The following code snippet defines a reusable animation named `slideInAnimation`.
|
||||
|
||||
|
||||
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts" region="route-animations" language="typescript"></code-example>
|
||||
|
||||
The animation definition does several things:
|
||||
|
||||
* Defines two transitions. A single trigger can define multiple states and transitions.
|
||||
* Adjusts the styles of the host and child views to control their relative positions during the transition.
|
||||
* Uses `query()` to determine which child view is entering and which is leaving the host view.
|
||||
|
||||
A route change activates the animation trigger, and a transition matching the state change is applied.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The transition states must match the `data` property value defined in the route configuration.
|
||||
</div>
|
||||
|
||||
Make the animation definition available in your application by adding the reusable animation (`slideInAnimation`) to the `animations` metadata of the `AppComponent`.
|
||||
|
||||
<code-example path="animations/src/app/app.component.ts" header="src/app/app.component.ts" region="define" language="typescript"></code-example>
|
||||
|
||||
### Styling the host and child components
|
||||
|
||||
During a transition, a new view is inserted directly after the old one and both elements appear on screen at the same time. To prevent this, apply additional styling to the host view, and to the removed and inserted child views. The host view must use relative positioning, and the child views must use absolute positioning. Adding styling to the views animates the containers in place, without the DOM moving things around.
|
||||
|
||||
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts" region="style-view" language="typescript"></code-example>
|
||||
|
||||
### Querying the view containers
|
||||
|
||||
Use the `query()` method to find and animate elements within the current host component. The `query(":enter")` statement returns the view that is being inserted, and `query(":leave")` returns the view that is being removed.
|
||||
|
||||
Let's assume that we are routing from the *Home => About*.
|
||||
|
||||
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts (Continuation from above)" region="query" language="typescript"></code-example>
|
||||
|
||||
The animation code does the following after styling the views:
|
||||
|
||||
* `query(':enter', style({ left: '-100%' }))` matches the view that is added and hides the newly added view by positioning it to the far left.
|
||||
* Calls `animateChild()` on the view that is leaving, to run its child animations.
|
||||
* Uses `group()` function to make the inner animations run in parallel.
|
||||
* Within the `group()` function:
|
||||
* Queries the view that is removed and animates it to slide far to the right.
|
||||
* Slides in the new view by animating the view with an easing function and duration. </br>
|
||||
This animation results in the `about` view sliding from the left to right.
|
||||
* Calls the `animateChild()` method on the new view to run its child animations after the main animation completes.
|
||||
|
||||
You now have a basic routable animation that animates routing from one view to another.
|
||||
|
||||
## More on Angular animations
|
||||
|
||||
You may also be interested in the following:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
* [Complex animation sequences](guide/complex-animation-sequences)
|
||||
* [Reusable animations](guide/reusable-animations)
|
@ -1,27 +1,26 @@
|
||||
# Route transition animations
|
||||
# Animaciones para transición de rutas
|
||||
|
||||
#### Prerequisites
|
||||
#### Prerrequisitos
|
||||
|
||||
A basic understanding of the following concepts:
|
||||
Una comprensión basica de los siguientes conceptos:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
* [Reusable animations](guide/reusable-animations)
|
||||
* [Introducción a animaciones en Angular](guide/animations)
|
||||
* [Transición y desencadenadores](guide/transition-and-triggers)
|
||||
* [Animaciones reutilizables](guide/reusable-animations)
|
||||
|
||||
<hr>
|
||||
|
||||
Routing enables users to navigate between different routes in an application. When a user navigates from one route to another, the Angular router maps the URL path to a relevant component and displays its view. Animating this route transition can greatly enhance the user experience.
|
||||
Enrutar permite a los usuarios navegar entre diferentes rutas de una aplicación. Cuando un usuario navega de una ruta a otra, el enrutador de Angular traza el trayecto de la URL a un componente importante y se muestra en su vista. Animar esta transición de rutas puede mejorar mucho la experiencia del usuario.
|
||||
|
||||
The Angular router comes with high-level animation functions that let you animate the transitions between views when a route changes. To produce an animation sequence when switching between routes, you need to define nested animation sequences. Start with the top-level component that hosts the view, and nest additional animations in the components that host the embedded views.
|
||||
El enrutador de Angular viene con funciones de animación de alto nivel que te permiten animar las transiciones entre vistas cuando una ruta cambia. Para producir una secuencia de animación al cambiar de ruta, necesitas definir secuencias de animación anidadas. Empieza con los componentes de alto nivel que contienen la vista, y anida animaciones adicionales en los componentes que contienen las vistas integradas.
|
||||
|
||||
To enable routing transition animation, do the following:
|
||||
Para permitir la animación de transición de rutas, haz lo siguiente:
|
||||
|
||||
1. Import the routing module into the application and create a routing configuration that defines the possible routes.
|
||||
2. Add a router outlet to tell the Angular router where to place the activated components in the DOM.
|
||||
3. Define the animation.
|
||||
1. Importa el módulo enrutado dentro de la aplicación y crea una configuración de enrutamiento que defina las posibles rutas.
|
||||
2. Añade un punto de salida del enrutador para indicarle al enrutador de Angular donde posicionar los componentes activados en el DOM.
|
||||
3. Define la animación.
|
||||
|
||||
|
||||
Let's illustrate a router transition animation by navigating between two routes, *Home* and *About* associated with the `HomeComponent` and `AboutComponent` views respectively. Both of these component views are children of the top-most view, hosted by `AppComponent`. We'll implement a router transition animation that slides in the new view to the right and slides out the old view when the user navigates between the two routes.
|
||||
Imaginemos un enrutador de animación de transiciones mediante la navegación entre dos rutas, *Home* y *About* asociadas con las vistas `HomeComponent` y `AboutComponent` respectivamente. Estos dos componentes de vista son hijos de la vista superior, contenida por `AppComponent`. Implementaremos un enrutador de animación de transiciones que desliza dentro la nueva vista hacia la derecha y desliza fuera la vista anterior cuando el usuario navega entre las dos rutas.
|
||||
|
||||
</br>
|
||||
|
||||
@ -29,104 +28,104 @@ Let's illustrate a router transition animation by navigating between two routes,
|
||||
<img src="generated/images/guide/animations/route-animation.gif" alt="Animations in action" width="440">
|
||||
</div>
|
||||
|
||||
## Route configuration
|
||||
## Configuración de rutas
|
||||
|
||||
To begin, configure a set of routes using methods available in the `RouterModule` class. This route configuration tells the router how to navigate.
|
||||
Para empezar, configura un grupo de rutas usando los métodos disponibles en la clase `RouterModule`. Esta configuración de rutas le indica al enrutador cómo navegar.
|
||||
|
||||
Use the `RouterModule.forRoot` method to define a set of routes. Also, import this `RouterModule` to the `imports` array of the main module, `AppModule`.
|
||||
Usa el método `RouterModule.forRoot` para definir un grupo de rutas. También, importa este `RouterModule` al array `imports` del módulo principal, `AppModule`.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** Use the `RouterModule.forRoot` method in the root module, `AppModule`, to register top-level application routes and providers. For feature modules, call the `RouterModule.forChild` method to register additional routes.
|
||||
**Nota:** Usa el método `RouterModule.forRoot` en el módulo raíz, `AppModule`, para registrar rutas y proveedores de nivel superior de la aplicación. Para los módulos de funcionalidad, llama el método `RouterModule.forChild` para registrar rutas adicionales.
|
||||
|
||||
</div>
|
||||
|
||||
The following configuration defines the possible routes for the application.
|
||||
La siguiente configuración define las posibles rutas para la aplicación.
|
||||
|
||||
<code-example path="animations/src/app/app.module.ts" header="src/app/app.module.ts" region="route-animation-data" language="typescript"></code-example>
|
||||
|
||||
The `home` and `about` paths are associated with the `HomeComponent` and `AboutComponent` views. The route configuration tells the Angular router to instantiate the `HomeComponent` and `AboutComponent` views when the navigation matches the corresponding path.
|
||||
Las rutas `home` y `about` están asociadas con las vistas `HomeComponent` y `AboutComponent`. La configuración de rutas le indica al enrutador de Angular que instancie las vistas `HomeComponent` y `AboutComponent` cuando la navegación coincide con la ruta correspondiente.
|
||||
|
||||
In addition to `path` and `component`, the `data` property of each route defines the key animation-specific configuration associated with a route. The `data` property value is passed into `AppComponent` when the route changes. You can also pass additional data in route config that is consumed within the animation. The data property value has to match the transitions defined in the `routeAnimation` trigger, which we'll define later.
|
||||
A parte de `path` y `component`, la propiedad `data` de cada ruta define la configuración clave específica de la animación asociada con la ruta. El valor de la propiedad `data` se pasa a `AppComponent` cuando la ruta cambia. También puedes pasar datos adicionales en la configuración de la ruta que se consumen dentro de la animación. El valor de la propiedad data tiene que coincidir con las transiciones definidas en el desencadenador `routeAnimation`, que definiremos más adelante.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The `data` property names that you use can be arbitrary. For example, the name *animation* used in the example above is an arbitrary choice.
|
||||
**Nota:** Los nombres de las propiedades `data` que se utilizan pueden ser arbitrarios. Por ejemplo, el nombre *animación* utilizado en el ejemplo anterior es una elección arbitraria.
|
||||
|
||||
</div>
|
||||
|
||||
## Router outlet
|
||||
## Punto de salida del enrutador
|
||||
|
||||
After configuring the routes, tell the Angular router where to render the views when matched with a route. You can set a router outlet by inserting a `<router-outlet>` container inside the root `AppComponent` template.
|
||||
Después de configurar las rutas, indícale al enrutador de Angular dónde renderizar las vistas cuando coincidan con una ruta. Puedes establecer un punto de salida del enrutador insertando un contenedor `<router-outlet>` dentro de la plantilla raíz `AppComponent`.
|
||||
|
||||
The `<router-outlet>` container has an attribute directive that contains data about active routes and their states, based on the `data` property that we set in the route configuration.
|
||||
El contenedor `<router-outlet>` tiene una directiva de atributos que contiene datos sobre las rutas activas y sus estados, basados en la propiedad `data` que establecimos en la configuración de la ruta.
|
||||
|
||||
<code-example path="animations/src/app/app.component.html" header="src/app/app.component.html" region="route-animations-outlet"></code-example>
|
||||
|
||||
`AppComponent` defines a method that can detect when a view changes. The method assigns an animation state value to the animation trigger (`@routeAnimation`) based on the route configuration `data` property value. Here's an example of an `AppComponent` method that detects when a route change happens.
|
||||
El `AppComponent` define un método que puede detectar cuando una vista cambia. El método asigna un valor de estado de animación al desencadenador de animación (`@routeAnimation`) basado en el valor de la propiedad `data` de configuración de la ruta. Aquí tienes un ejemplo de un método de `AppComponent` que detecta cuando se produce un cambio de ruta.
|
||||
|
||||
<code-example path="animations/src/app/app.component.ts" header="src/app/app.component.ts" region="prepare-router-outlet" language="typescript"></code-example>
|
||||
|
||||
Here, the `prepareRoute()` method takes the value of the outlet directive (established through `#outlet="outlet"`) and returns a string value representing the state of the animation based on the custom data of the current active route. You can use this data to control which transition to execute for each route.
|
||||
En este caso, el método `prepareRoute()` toma el valor de la directiva del punto de salida (establecido a través de `#outlet="outlet"`) y devuelve un valor de cadena que representa el estado de la animación basado en los datos personalizados de la ruta activa actual. Puedes utilizar estos datos para controlar qué transición ejecutar para cada ruta.
|
||||
|
||||
## Animation definition
|
||||
## Definición de la animación
|
||||
|
||||
Animations can be defined directly inside your components. For this example we are defining the animations in a separate file, which allows us to re-use the animations.
|
||||
|
||||
The following code snippet defines a reusable animation named `slideInAnimation`.
|
||||
Las animaciones pueden ser definidas directamente dentro de tus componentes. Para este ejemplo estamos definiendo las animaciones en un archivo separado, lo que nos permite reutilizar las animaciones.
|
||||
|
||||
El siguiente fragmento de código define una animación reutilizable llamada `slideInAnimation`.
|
||||
|
||||
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts" region="route-animations" language="typescript"></code-example>
|
||||
|
||||
The animation definition does several things:
|
||||
La definición de animación hace varias cosas:
|
||||
|
||||
* Defines two transitions. A single trigger can define multiple states and transitions.
|
||||
* Adjusts the styles of the host and child views to control their relative positions during the transition.
|
||||
* Uses `query()` to determine which child view is entering and which is leaving the host view.
|
||||
* Define dos transiciones. Un solo desencadenador puede definir múltiples estados y transiciones.
|
||||
* Ajusta los estilos de las vistas anfitriona e hija para controlar sus posiciones relativas durante la transición.
|
||||
* Utiliza `query()` para determinar qué vista hija está entrando y cuál está saliendo de la vista anfitriona.
|
||||
|
||||
A route change activates the animation trigger, and a transition matching the state change is applied.
|
||||
Un cambio de ruta activa el desencadenante de la animación, y se aplica una transición que coincide con el cambio de estado.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** The transition states must match the `data` property value defined in the route configuration.
|
||||
**Nota:** Los estados de transición deben coincidir con el valor de la propiedad `data` definida en la configuración de la ruta.
|
||||
|
||||
</div>
|
||||
|
||||
Make the animation definition available in your application by adding the reusable animation (`slideInAnimation`) to the `animations` metadata of the `AppComponent`.
|
||||
Haz que la definición de la animación esté disponible en tu aplicación añadiendo la animación reutilizable (`slideInAnimation`) a los metadatos `animations` del `AppComponent`.
|
||||
|
||||
<code-example path="animations/src/app/app.component.ts" header="src/app/app.component.ts" region="define" language="typescript"></code-example>
|
||||
|
||||
### Styling the host and child components
|
||||
### Estilos de los componentes anfitrión e hijo
|
||||
|
||||
During a transition, a new view is inserted directly after the old one and both elements appear on screen at the same time. To prevent this, apply additional styling to the host view, and to the removed and inserted child views. The host view must use relative positioning, and the child views must use absolute positioning. Adding styling to the views animates the containers in place, without the DOM moving things around.
|
||||
Durante una transición, se inserta una nueva vista directamente después de la anterior y ambos elementos aparecen en pantalla al mismo tiempo. Para evitarlo, aplica un estilo adicional a la vista anfitriona y a las vistas hijas eliminadas e insertadas. La vista anfitriona debe utilizar posicionamiento relativo, y las vistas hijas deben utilizar posicionamiento absoluto. Añadir estilos a las vistas anima los contenedores en su lugar, sin que el DOM mueva las cosas.
|
||||
|
||||
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts" region="style-view" language="typescript"></code-example>
|
||||
|
||||
### Querying the view containers
|
||||
### Consultas de los contenedores de la vista
|
||||
|
||||
Use the `query()` method to find and animate elements within the current host component. The `query(":enter")` statement returns the view that is being inserted, and `query(":leave")` returns the view that is being removed.
|
||||
Utiliza el método `query()` para encontrar y animar elementos dentro del componente anfitrión actual. La sentencia `query(":enter")` devuelve la vista que se está insertando, y `query(":leave")` devuelve la vista que se está eliminando.
|
||||
|
||||
Let's assume that we are routing from the *Home => About*.
|
||||
Supongamos que estamos enrutando desde *Home => About*.
|
||||
|
||||
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts (Continuation from above)" region="query" language="typescript"></code-example>
|
||||
|
||||
The animation code does the following after styling the views:
|
||||
El código de animación hace lo siguiente después de estilizar las vistas:
|
||||
|
||||
* `query(':enter', style({ left: '-100%' }))` matches the view that is added and hides the newly added view by positioning it to the far left.
|
||||
* Calls `animateChild()` on the view that is leaving, to run its child animations.
|
||||
* Uses `group()` function to make the inner animations run in parallel.
|
||||
* Within the `group()` function:
|
||||
* Queries the view that is removed and animates it to slide far to the right.
|
||||
* Slides in the new view by animating the view with an easing function and duration. </br>
|
||||
This animation results in the `about` view sliding from the left to right.
|
||||
* Calls the `animateChild()` method on the new view to run its child animations after the main animation completes.
|
||||
* `query(':enter', style({ left: '-100%' }))` coincide con la vista que se añade y oculta la nueva vista añadida posicionándola en el extremo izquierdo.
|
||||
* Llama a `animateChild()` en la vista que se va, para ejecutar las animaciones de sus hijos.
|
||||
* Utiliza la función `group()` para hacer que las animaciones internas se ejecuten en paralelo.
|
||||
* Dentro de la función `group()`:
|
||||
* Consulta la vista que se elimina y la anima para que se deslice hacia la derecha.
|
||||
* Desliza la nueva vista animando la vista con una función de suavizado y duración. </br>
|
||||
Esta animación hace que la vista `about` se deslice de izquierda a derecha.
|
||||
* Llama al método `animateChild()` en la nueva vista para ejecutar sus animaciones hijas después de que la animación principal se complete.
|
||||
|
||||
You now have a basic routable animation that animates routing from one view to another.
|
||||
Ahora tienes una animación básica que anima el enrutado de una vista a otra.
|
||||
|
||||
## More on Angular animations
|
||||
## Más información sobre las animaciones de Angular
|
||||
|
||||
You may also be interested in the following:
|
||||
También puede interesarte lo siguiente:
|
||||
|
||||
* [Introduction to Angular animations](guide/animations)
|
||||
* [Transition and triggers](guide/transition-and-triggers)
|
||||
* [Complex animation sequences](guide/complex-animation-sequences)
|
||||
* [Reusable animations](guide/reusable-animations)
|
||||
* [Introducción a las animaciones de Angular](guide/animations)
|
||||
* [Transición y desencadenadores](guide/transition-and-triggers)
|
||||
* [Secuencias de animación complejas](guide/complex-animation-sequences)
|
||||
* [Animaciones reutilizables](guide/reusable-animations)
|
||||
|
97
aio/content/guide/rx-library.en.md
Normal file
97
aio/content/guide/rx-library.en.md
Normal file
@ -0,0 +1,97 @@
|
||||
# The RxJS library
|
||||
|
||||
Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change ([Wikipedia](https://en.wikipedia.org/wiki/Reactive_programming)). RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. See ([RxJS Docs](https://rxjs.dev/guide/overview)).
|
||||
|
||||
RxJS provides an implementation of the `Observable` type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables. These utility functions can be used for:
|
||||
|
||||
* Converting existing code for async operations into observables
|
||||
* Iterating through the values in a stream
|
||||
* Mapping values to different types
|
||||
* Filtering streams
|
||||
* Composing multiple streams
|
||||
|
||||
## Observable creation functions
|
||||
|
||||
RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on. For example:
|
||||
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="promise" header="Create an observable from a promise"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="interval" header="Create an observable from a counter"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="event" header="Create an observable from an event"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="ajax" header="Create an observable that creates an AJAX request"></code-example>
|
||||
|
||||
## Operators
|
||||
|
||||
Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections. For example, RxJS defines operators such as `map()`, `filter()`, `concat()`, and `flatMap()`.
|
||||
|
||||
Operators take configuration options, and they return a function that takes a source observable. When executing this returned function, the operator observes the source observable’s emitted values, transforms them, and returns a new observable of those transformed values. Here is a simple example:
|
||||
|
||||
<code-example path="rx-library/src/operators.ts" header="Map operator"></code-example>
|
||||
|
||||
You can use _pipes_ to link operators together. Pipes let you combine multiple functions into a single function. The `pipe()` function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
|
||||
|
||||
A set of operators applied to an observable is a recipe—that is, a set of instructions for producing the values you’re interested in. By itself, the recipe doesn’t do anything. You need to call `subscribe()` to produce a result through the recipe.
|
||||
|
||||
Here’s an example:
|
||||
|
||||
<code-example path="rx-library/src/operators.1.ts" header="Standalone pipe function"></code-example>
|
||||
|
||||
The `pipe()` function is also a method on the RxJS `Observable`, so you use this shorter form to define the same operation:
|
||||
|
||||
<code-example path="rx-library/src/operators.2.ts" header="Observable.pipe function"></code-example>
|
||||
|
||||
### Common operators
|
||||
|
||||
RxJS provides many operators, but only a handful are used frequently. For a list of operators and usage samples, visit the [RxJS API Documentation](https://rxjs.dev/api).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
Note that, for Angular apps, we prefer combining operators with pipes, rather than chaining. Chaining is used in many RxJS examples.
|
||||
</div>
|
||||
|
||||
| Area | Operators |
|
||||
| :------------| :----------|
|
||||
| Creation | `from`,`fromEvent`, `of` |
|
||||
| Combination | `combineLatest`, `concat`, `merge`, `startWith` , `withLatestFrom`, `zip` |
|
||||
| Filtering | `debounceTime`, `distinctUntilChanged`, `filter`, `take`, `takeUntil` |
|
||||
| Transformation | `bufferTime`, `concatMap`, `map`, `mergeMap`, `scan`, `switchMap` |
|
||||
| Utility | `tap` |
|
||||
| Multicasting | `share` |
|
||||
|
||||
## Error handling
|
||||
|
||||
In addition to the `error()` handler that you provide on subscription, RxJS provides the `catchError` operator that lets you handle known errors in the observable recipe.
|
||||
|
||||
For instance, suppose you have an observable that makes an API request and maps to the response from the server. If the server returns an error or the value doesn’t exist, an error is produced. If you catch this error and supply a default value, your stream continues to process values rather than erroring out.
|
||||
|
||||
Here's an example of using the `catchError` operator to do this:
|
||||
|
||||
<code-example path="rx-library/src/error-handling.ts" header="catchError operator"></code-example>
|
||||
|
||||
### Retry failed observable
|
||||
|
||||
Where the `catchError` operator provides a simple path of recovery, the `retry` operator lets you retry a failed request.
|
||||
|
||||
Use the `retry` operator before the `catchError` operator. It resubscribes to the original source observable, which can then re-run the full sequence of actions that resulted in the error. If this includes an HTTP request, it will retry that HTTP request.
|
||||
|
||||
The following converts the previous example to retry the request before catching the error:
|
||||
|
||||
<code-example path="rx-library/src/retry-on-error.ts" header="retry operator"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Do not retry **authentication** requests, since these should only be initiated by user action. We don't want to lock out user accounts with repeated login requests that the user has not initiated.
|
||||
|
||||
</div>
|
||||
|
||||
## Naming conventions for observables
|
||||
|
||||
Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.
|
||||
|
||||
This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.
|
||||
|
||||
For example:
|
||||
|
||||
<code-example path="rx-library/src/naming-convention.ts" header="Naming observables"></code-example>
|
@ -1,97 +1,98 @@
|
||||
# The RxJS library
|
||||
# La Librería de RxJS
|
||||
|
||||
Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change ([Wikipedia](https://en.wikipedia.org/wiki/Reactive_programming)). RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. See ([RxJS Docs](https://rxjs.dev/guide/overview)).
|
||||
La programación Reactiva es un paradigma de programación asincrónico interesado en los flujos de datos y la propagación al cambio ([Wikipedia](https://en.wikipedia.org/wiki/Reactive_programming)). RxJS (Por sus siglas en Inglés, "Reactive Extensions for JavaScript") es una librería para programación reactiva usando obvservables que hacen más fácil la creación de código asincrono o basado en callbacks. Ver ([RxJS Docs](https://rxjs.dev/guide/overview)).
|
||||
|
||||
RxJS provides an implementation of the `Observable` type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables. These utility functions can be used for:
|
||||
RxJS proporciona una implementación del tipo `Observable`, el cual es necesitado hasta que el tipo de dato sea parte del lenguaje y hasta que los navegadores ofrezcan un soporte. La librería también proporciona funciones de utilería para la creación y trabajo con observables. Dichas funciones de utilería pueden ser usadas para:
|
||||
|
||||
* Converting existing code for async operations into observables
|
||||
* Iterating through the values in a stream
|
||||
* Mapping values to different types
|
||||
* Filtering streams
|
||||
* Composing multiple streams
|
||||
* Convertir código existente para operaciones asíncronas en observables.
|
||||
* Iterar a través de valores en un flujo de datos.
|
||||
* Mappear valores en tipos de datos diferentes.
|
||||
* Filtrar flujos de datos.
|
||||
* Composición de múltiplos flujos.
|
||||
|
||||
## Observable creation functions
|
||||
## Creación de funciones observables
|
||||
|
||||
RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on. For example:
|
||||
RxJS ofrece un sin fin de funciones que pueden ser usadas para crear nuevos observables. Estas funciones pueden simplificar el proceso de creación de observables desde cosas como eventos, temporizadores, promesas, etc. Por ejemplo:
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="promise" header="Crear un observable desde una promesa"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="promise" header="Create an observable from a promise"></code-example>
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="interval" header="Crear un observable desde un contador"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="interval" header="Create an observable from a counter"></code-example>
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="event" header="Crear un observable desde un evento"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="event" header="Create an observable from an event"></code-example>
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="ajax" header="Crear un observable que crea una petición AJAX"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/simple-creation.ts" region="ajax" header="Create an observable that creates an AJAX request"></code-example>
|
||||
{@a operators}
|
||||
## Operadores
|
||||
|
||||
## Operators
|
||||
Los operadores son funciones que construyen sobre la fundación de los observables para tener una manipulación más sofisticada de las colecciones. Por ejemplo, RxJS define operadores como `map()`, `filter()`, `concat()`, y `flatMap()`.
|
||||
|
||||
Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections. For example, RxJS defines operators such as `map()`, `filter()`, `concat()`, and `flatMap()`.
|
||||
Los operadores toman las opciones de configuración y después regresan una función que toma la fuente observable. Cuando ejecutamos esta función regresada, el operador observa los valores fuente emitidos por el observable, los transforma y regresa un nuevo observable de esos valores transformados. Aquí un ejemplo sencillo:
|
||||
|
||||
Operators take configuration options, and they return a function that takes a source observable. When executing this returned function, the operator observes the source observable’s emitted values, transforms them, and returns a new observable of those transformed values. Here is a simple example:
|
||||
<code-example path="rx-library/src/operators.ts" header="Operador Map"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/operators.ts" header="Map operator"></code-example>
|
||||
Puedes usar _pipes_ para enlazar más de un operador. Los Pipes te permiten combinar múltiples funciones en una sola. La función `pipe()` tiene como argumentos las funciones que quieres que combine y regresa una nueva función que, una vez ejecutada, corre las funciones en una sequencia.
|
||||
|
||||
You can use _pipes_ to link operators together. Pipes let you combine multiple functions into a single function. The `pipe()` function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
|
||||
Un conjunto de operadores aplicados a un observable no es más que una receta la cuál, es un conjunto de instrucciones para producir los valores que te interesan. Por sí misma, esta receta no hace nada. Necesitarás llamar a la función `subscribe()` para producir un resultado a través dicha receta.
|
||||
|
||||
A set of operators applied to an observable is a recipe—that is, a set of instructions for producing the values you’re interested in. By itself, the recipe doesn’t do anything. You need to call `subscribe()` to produce a result through the recipe.
|
||||
A continuación un ejemplo:
|
||||
|
||||
Here’s an example:
|
||||
<code-example path="rx-library/src/operators.1.ts" header="Función pipe autónoma"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/operators.1.ts" header="Standalone pipe function"></code-example>
|
||||
La función `pipe()` es también un `Observable` en RxJS, así que usas esta manera más sencilla para definir la misma operación:
|
||||
|
||||
The `pipe()` function is also a method on the RxJS `Observable`, so you use this shorter form to define the same operation:
|
||||
<code-example path="rx-library/src/operators.2.ts" header="Función Observable.pipe"></code-example>
|
||||
|
||||
<code-example path="rx-library/src/operators.2.ts" header="Observable.pipe function"></code-example>
|
||||
### Operadores Comunes
|
||||
|
||||
### Common operators
|
||||
|
||||
RxJS provides many operators, but only a handful are used frequently. For a list of operators and usage samples, visit the [RxJS API Documentation](https://rxjs.dev/api).
|
||||
RxJS propociona muchos operadores pero solo algunos se usan con frecuencia. Para una lista de los operadores y su uso visita la [Documentación de RxJS](https://rxjs.dev/api).
|
||||
|
||||
<div class="alert is-helpful">
|
||||
Note that, for Angular apps, we prefer combining operators with pipes, rather than chaining. Chaining is used in many RxJS examples.
|
||||
Nota: Para aplicaciones creadas con Angular preferiremos combinar operadores con pipes, en lugar de hacer cadenas. El encadenamiento es usado en muchos ejemplos de RxJS.
|
||||
</div>
|
||||
|
||||
| Area | Operators |
|
||||
| Area | Operador |
|
||||
| :------------| :----------|
|
||||
| Creation | `from`,`fromEvent`, `of` |
|
||||
| Combination | `combineLatest`, `concat`, `merge`, `startWith` , `withLatestFrom`, `zip` |
|
||||
| Filtering | `debounceTime`, `distinctUntilChanged`, `filter`, `take`, `takeUntil` |
|
||||
| Transformation | `bufferTime`, `concatMap`, `map`, `mergeMap`, `scan`, `switchMap` |
|
||||
| Utility | `tap` |
|
||||
| Multicasting | `share` |
|
||||
| Creación | `from`,`fromEvent`, `of` |
|
||||
| Combinación | `combineLatest`, `concat`, `merge`, `startWith` , `withLatestFrom`, `zip` |
|
||||
| Filtrado| `debounceTime`, `distinctUntilChanged`, `filter`, `take`, `takeUntil` |
|
||||
| Transformación | `bufferTime`, `concatMap`, `map`, `mergeMap`, `scan`, `switchMap` |
|
||||
| Utilería | `tap` |
|
||||
| Multidifusión | `share` |
|
||||
|
||||
## Error handling
|
||||
## Manejo de Errores
|
||||
|
||||
In addition to the `error()` handler that you provide on subscription, RxJS provides the `catchError` operator that lets you handle known errors in the observable recipe.
|
||||
En adición con el manejador de `error()` que te ayuda con la subscripción, RxJS proporciona el operador `catchError` que te permite manejar los errores conocidos en un medio de observables.
|
||||
|
||||
For instance, suppose you have an observable that makes an API request and maps to the response from the server. If the server returns an error or the value doesn’t exist, an error is produced. If you catch this error and supply a default value, your stream continues to process values rather than erroring out.
|
||||
Por ejemplo, supongamos que tienes un observable que hace una petición a una API y mapea la respuesta de un servidor. Si el servidor regresa un error o el valor no existe entonces se produciría un error. Si hacemos un catch de este error y le proporcionamos un valor por defecto entonces el flujo continuará, en lugar de simplemente mandarnos un error.
|
||||
|
||||
Here's an example of using the `catchError` operator to do this:
|
||||
|
||||
<code-example path="rx-library/src/error-handling.ts" header="catchError operator"></code-example>
|
||||
Aquí un ejemplo de como usar el operador `catchError` para hacer esto:
|
||||
|
||||
### Retry failed observable
|
||||
<code-example path="rx-library/src/error-handling.ts" header="Operador catchError"></code-example>
|
||||
|
||||
Where the `catchError` operator provides a simple path of recovery, the `retry` operator lets you retry a failed request.
|
||||
### Observable de reintentos fallidos
|
||||
|
||||
Use the `retry` operator before the `catchError` operator. It resubscribes to the original source observable, which can then re-run the full sequence of actions that resulted in the error. If this includes an HTTP request, it will retry that HTTP request.
|
||||
Donde el operador `catchError` ayuda a crear un camino simple para recuperarnos, el operador `retry` te permite reintentar una petición fallida.
|
||||
|
||||
The following converts the previous example to retry the request before catching the error:
|
||||
Usa el operador `retry` antes del operador `catchError`. Dicho operador te re-subscribe a la fuente original del observable, la cual puede re-ejecutar una secuencia llena de acciones que resultaron en el error en primer lugar. Si esto incluye una petición HTTP, entonces el operador reintentará hacer la petición HTTP.
|
||||
|
||||
<code-example path="rx-library/src/retry-on-error.ts" header="retry operator"></code-example>
|
||||
En el siguiente ejemplo usamos el ejemplo anterior pero ahora intentamos hacer la petición primero antes de obtener el error.
|
||||
|
||||
<code-example path="rx-library/src/retry-on-error.ts" header="Operador retry"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Do not retry **authentication** requests, since these should only be initiated by user action. We don't want to lock out user accounts with repeated login requests that the user has not initiated.
|
||||
No intentar hacer peticiones con una **autenticación** , ya que estas deben ser inicialiadas por una acción del usuario. No nos gustaría bloquear cuentas de usuario con solicitudes de inicio de sesión repetidas que el mismo usuario no ha iniciado.
|
||||
|
||||
</div>
|
||||
|
||||
## Naming conventions for observables
|
||||
## Nombrando convenciones para los observables
|
||||
|
||||
Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.
|
||||
Debido a que en su mayoría las aplicaciones de Angular están escritas en TypeScript, típicamente sabrás cuando una variable es un observable. Aunque el framework de Angular no impone una convención de nombrado de observables, frecuentemente veras a los observables nombrados con el signo de “$” al final.
|
||||
|
||||
This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.
|
||||
Esto puede llegar a ser muy útil cuando escaneamos rapidamente el código y miramos el valor de los observables. Además, si quieres tener una propiedad para almacenara el valor más reciente de un observable entonce puede ser muy conveniente simplemente usar el nombre con o sin el “$”.
|
||||
|
||||
For example:
|
||||
Por ejemplo:
|
||||
|
||||
<code-example path="rx-library/src/naming-convention.ts" header="Naming observables"></code-example>
|
||||
<code-example path="rx-library/src/naming-convention.ts" header="Nombrando observables"></code-example>
|
||||
|
121
aio/content/guide/schematics.en.md
Normal file
121
aio/content/guide/schematics.en.md
Normal file
@ -0,0 +1,121 @@
|
||||
# Generating code using schematics
|
||||
|
||||
A schematic is a template-based code generator that supports complex logic.
|
||||
It is a set of instructions for transforming a software project by generating or modifying code.
|
||||
Schematics are packaged into [collections](guide/glossary#collection) and installed with npm.
|
||||
|
||||
The schematic collection can be a powerful tool for creating, modifying, and maintaining any software project, but is particularly useful for customizing Angular projects to suit the particular needs of your own organization.
|
||||
You might use schematics, for example, to generate commonly-used UI patterns or specific components, using predefined templates or layouts.
|
||||
You can use schematics to enforce architectural rules and conventions, making your projects consistent and inter-operative.
|
||||
|
||||
## Schematics for the Angular CLI
|
||||
|
||||
Schematics are part of the Angular ecosystem. The [Angular CLI](guide/glossary#cli) uses schematics to apply transforms to a web-app project.
|
||||
You can modify these schematics, and define new ones to do things like update your code to fix breaking changes in a dependency, for example, or to add a new configuration option or framework to an existing project.
|
||||
|
||||
Schematics that are included in the `@schematics/angular` collection are run by default by the commands `ng generate` and `ng add`.
|
||||
The package contains named schematics that configure the options that are available to the CLI for `ng generate` sub-commands, such as `ng generate component` and `ng generate service`.
|
||||
The subcommands for `ng generate` are shorthand for the corresponding schematic. You can specify a particular schematic (or collection of schematics) to generate, using the long form:
|
||||
|
||||
<code-example language="bash">
|
||||
ng generate my-schematic-collection:my-schematic-name
|
||||
</code-example>
|
||||
|
||||
or
|
||||
|
||||
<code-example language="bash">
|
||||
ng generate my-schematic-name --collection collection-name
|
||||
</code-example>
|
||||
|
||||
### Configuring CLI schematics
|
||||
|
||||
A JSON schema associated with a schematic tells the Angular CLI what options are available to commands and subcommands, and determines the defaults.
|
||||
These defaults can be overridden by providing a different value for an option on the command line.
|
||||
See [Workspace Configuration](guide/workspace-config) for information about how you can change the generation option defaults for your workspace.
|
||||
|
||||
The JSON schemas for the default schematics used by the CLI to generate projects and parts of projects are collected in the package [`@schematics/angular`](https://raw.githubusercontent.com/angular/angular-cli/v7.0.0/packages/schematics/angular/application/schema.json).
|
||||
The schema describes the options available to the CLI for each of the `ng generate` sub-commands, as shown in the `--help` output.
|
||||
|
||||
## Developing schematics for libraries
|
||||
|
||||
As a library developer, you can create your own collections of custom schematics to integrate your library with the Angular CLI.
|
||||
|
||||
* An *add schematic* allows developers to install your library in an Angular workspace using `ng add`.
|
||||
|
||||
* *Generation schematics* can tell the `ng generate` subcommands how to modify projects, add configurations and scripts, and scaffold artifacts that are defined in your library.
|
||||
|
||||
* An *update schematic* can tell the `ng update` command how to update your library's dependencies and adjust for breaking changes when you release a new version.
|
||||
|
||||
For more details of what these look like and how to create them, see:
|
||||
* [Authoring Schematics](guide/schematics-authoring)
|
||||
* [Schematics for Libraries](guide/schematics-for-libraries)
|
||||
|
||||
### Add schematics
|
||||
|
||||
An add schematic is typically supplied with a library, so that the library can be added to an existing project with `ng add`.
|
||||
The `add` command uses your package manager to download new dependencies, and invokes an installation script that is implemented as a schematic.
|
||||
|
||||
For example, the [`@angular/material`](https://material.angular.io/guide/schematics) schematic tells the `add` command to install and set up Angular Material and theming, and register new starter components that can be created with `ng generate`.
|
||||
You can look at this one as an example and model for your own add schematic.
|
||||
|
||||
Partner and third party libraries also support the Angular CLI with add schematics.
|
||||
For example, `@ng-bootstrap/schematics` adds [ng-bootstrap](https://ng-bootstrap.github.io/) to an app, and `@clr/angular` installs and sets up [Clarity from VMWare](https://vmware.github.io/clarity/documentation/v1.0/get-started).
|
||||
|
||||
An add schematic can also update a project with configuration changes, add additional dependencies (such as polyfills), or scaffold package-specific initialization code.
|
||||
For example, the `@angular/pwa` schematic turns your application into a PWA by adding an app manifest and service worker, and the `@angular/elements` schematic adds the `document-register-element.js` polyfill and dependencies for Angular Elements.
|
||||
|
||||
### Generation schematics
|
||||
|
||||
Generation schematics are instructions for the `ng generate` command.
|
||||
The documented sub-commands use the default Angular generation schematics, but you can specify a different schematic (in place of a sub-command) to generate an artifact defined in your library.
|
||||
|
||||
Angular Material, for example, supplies generation schematics for the UI components that it defines.
|
||||
The following command uses one of these schematics to render an Angular Material `<mat-table>` that is pre-configured with a datasource for sorting and pagination.
|
||||
|
||||
<code-example language="bash">
|
||||
ng generate @angular/material:table <component-name>
|
||||
</code-example>
|
||||
|
||||
### Update schematics
|
||||
|
||||
The `ng update` command can be used to update your workspace's library dependencies. If you supply no options or use the help option, the command examines your workspace and suggests libraries to update.
|
||||
|
||||
<code-example language="bash">
|
||||
ng update
|
||||
We analyzed your package.json, there are some packages to update:
|
||||
|
||||
Name Version Command to update
|
||||
--------------------------------------------------------------------------------
|
||||
@angular/cdk 7.2.2 -> 7.3.1 ng update @angular/cdk
|
||||
@angular/cli 7.2.3 -> 7.3.0 ng update @angular/cli
|
||||
@angular/core 7.2.2 -> 7.2.3 ng update @angular/core
|
||||
@angular/material 7.2.2 -> 7.3.1 ng update @angular/material
|
||||
rxjs 6.3.3 -> 6.4.0 ng update rxjs
|
||||
|
||||
|
||||
There might be additional packages that are outdated.
|
||||
Run "ng update --all" to try to update all at the same time.
|
||||
</code-example>
|
||||
|
||||
If you pass the command a set of libraries to update (or the `--all` flag), it updates those libraries, their peer dependencies, and the peer dependencies that depend on them.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
If there are inconsistencies (for example, if peer dependencies cannot be matched by a simple [semver](https://semver.io/) range), the command generates an error and does not change anything in the workspace.
|
||||
|
||||
We recommend that you do not force an update of all dependencies by default. Try updating specific dependencies first.
|
||||
|
||||
For more about how the `ng update` command works, see [Update Command](https://github.com/angular/angular-cli/blob/master/docs/specifications/update.md).
|
||||
|
||||
</div>
|
||||
|
||||
If you create a new version of your library that introduces potential breaking changes, you can provide an *update schematic* to enable the `ng update` command to automatically resolve any such changes in the project being updated.
|
||||
|
||||
For example, suppose you want to update the Angular Material library.
|
||||
|
||||
<code-example language="bash">
|
||||
ng update @angular/material
|
||||
</code-example>
|
||||
|
||||
This command updates both `@angular/material` and its dependency `@angular/cdk` in your workspace's `package.json`.
|
||||
If either package contains an update schematic that covers migration from the existing version to a new version, the command runs that schematic on your workspace.
|
@ -1,121 +1,128 @@
|
||||
# Generating code using schematics
|
||||
# Generando código usando esquemas
|
||||
|
||||
A schematic is a template-based code generator that supports complex logic.
|
||||
It is a set of instructions for transforming a software project by generating or modifying code.
|
||||
Schematics are packaged into [collections](guide/glossary#collection) and installed with npm.
|
||||
Un esquema es un generador de código basado en plantillas que soporta lógica compleja.
|
||||
Es un conjunto de instrucciones para transformar un proyecto de software, generando o modificando código.
|
||||
Los esquemas están en el paquete [collections](guide/glossary#collection) e instalados con npm.
|
||||
|
||||
The schematic collection can be a powerful tool for creating, modifying, and maintaining any software project, but is particularly useful for customizing Angular projects to suit the particular needs of your own organization.
|
||||
You might use schematics, for example, to generate commonly-used UI patterns or specific components, using predefined templates or layouts.
|
||||
You can use schematics to enforce architectural rules and conventions, making your projects consistent and inter-operative.
|
||||
La colección de esquemas puede ser una herramienta poderosa para la creación, modificación, y mantenimiento de cualquier proyecto de software, pero es particularmente útil para personalizar proyectos de Angular de acuerdo a las necesidades de tu propia organización.
|
||||
|
||||
## Schematics for the Angular CLI
|
||||
Podrías utilizar esquemas, por ejemplo, para generar patrones UI o componentes específicos, usando templates o layouts.
|
||||
Puedes usarlos también para hacer cumplir las reglas y convenciones arquitectónicas, haciendo que tus proyectos sean coherentes e inter operativos.
|
||||
|
||||
Schematics are part of the Angular ecosystem. The [Angular CLI](guide/glossary#cli) uses schematics to apply transforms to a web-app project.
|
||||
You can modify these schematics, and define new ones to do things like update your code to fix breaking changes in a dependency, for example, or to add a new configuration option or framework to an existing project.
|
||||
## Esquemas para Angular CLI
|
||||
|
||||
Schematics that are included in the `@schematics/angular` collection are run by default by the commands `ng generate` and `ng add`.
|
||||
The package contains named schematics that configure the options that are available to the CLI for `ng generate` sub-commands, such as `ng generate component` and `ng generate service`.
|
||||
The subcommands for `ng generate` are shorthand for the corresponding schematic. You can specify a particular schematic (or collection of schematics) to generate, using the long form:
|
||||
Los esquemas son parte del ecosistema de Angular, [Angular CLI](guide/glossary#cli) usa esquemas para aplicar transformaciones a proyectos web.
|
||||
|
||||
Tu puedes modificar estos esquemas, y definir nuevos para hacer cosas como actualizar tu código para corregir cambios importantes en una dependencia, o para agregar una nueva opción de configuración o bien un framework a un proyecto existente.
|
||||
|
||||
Los esquemas que se incluyen en la colección `@schematics/angular` se ejecutan de forma predeterminada por los comandos `ng generate` y `ng add`.
|
||||
|
||||
El paquete contiene esquemas con nombre que configuran las opciones que están disponibles en el CLI para los subcomandos `ng generate`, por ejemplo `ng generate component` y `ng generate service`.
|
||||
|
||||
Los subcomandos para `ng generate` son una abreviatura para el schema correspondiente. Puedes especificar un esquema particular (o colección de esquemas) para generar, utilizando la forma larga:
|
||||
|
||||
<code-example language="bash">
|
||||
ng generate my-schematic-collection:my-schematic-name
|
||||
</code-example>
|
||||
|
||||
or
|
||||
o
|
||||
|
||||
<code-example language="bash">
|
||||
ng generate my-schematic-name --collection collection-name
|
||||
</code-example>
|
||||
|
||||
### Configuring CLI schematics
|
||||
### Configuración de esquemas de CLI
|
||||
Un esquema JSON asociado con un esquema le dice a Angular CLI qué opciones están disponibles para comandos y subcomandos, y determina los valores predeterminados.
|
||||
|
||||
A JSON schema associated with a schematic tells the Angular CLI what options are available to commands and subcommands, and determines the defaults.
|
||||
These defaults can be overridden by providing a different value for an option on the command line.
|
||||
See [Workspace Configuration](guide/workspace-config) for information about how you can change the generation option defaults for your workspace.
|
||||
Estos valores predeterminados pueden ser sobrescritos para proporcionar un valor diferente para una opción en la línea de comandos.
|
||||
Puede ver [Configuración del espacio de trabajo](guide/workspace-config) para obtener información de cómo puedes cambiar la opción de generación predeterminada para tu espacion de trabajo.
|
||||
|
||||
The JSON schemas for the default schematics used by the CLI to generate projects and parts of projects are collected in the package [`@schematics/angular`](https://raw.githubusercontent.com/angular/angular-cli/v7.0.0/packages/schematics/angular/application/schema.json).
|
||||
The schema describes the options available to the CLI for each of the `ng generate` sub-commands, as shown in the `--help` output.
|
||||
Los esquemas JSON para los esquemas predeterminados que utiliza el CLI para generar proyectos y partes de proyectos están ubicados en el paquete [`@schematics/angular`](https://raw.githubusercontent.com/angular/angular-cli/v10.0.0/packages/schematics/angular/application/schema.json).
|
||||
|
||||
## Developing schematics for libraries
|
||||
El esquema describe las opciones disponibles para el CLI para cada subcomando de `ng generate`, como se muestra en la salida de `--help`.
|
||||
|
||||
As a library developer, you can create your own collections of custom schematics to integrate your library with the Angular CLI.
|
||||
## Desarrollo de esquemas para librerías.
|
||||
|
||||
* An *add schematic* allows developers to install your library in an Angular workspace using `ng add`.
|
||||
Como desarrollador de librerías, puedes crear tus propias colecciones con esquemas personalizados para integrar tus librerías con Angular CLI.
|
||||
|
||||
* *Generation schematics* can tell the `ng generate` subcommands how to modify projects, add configurations and scripts, and scaffold artifacts that are defined in your library.
|
||||
* Un *add schematic* permite a los desarrolladores instalar sus librería en un espacion de trabajo de Angular usando `ng add`.
|
||||
|
||||
* An *update schematic* can tell the `ng update` command how to update your library's dependencies and adjust for breaking changes when you release a new version.
|
||||
* *Generation schematics* puede decirle a los subcomandos de `ng generate` como modificar proyectos, configuraciones, scripts y la estructura de artefactos que están definidos en su librería.
|
||||
|
||||
For more details of what these look like and how to create them, see:
|
||||
* [Authoring Schematics](guide/schematics-authoring)
|
||||
* [Schematics for Libraries](guide/schematics-for-libraries)
|
||||
* Un *update schematic* puede decirle a los subcomandos de `ng update` como modificar las dependencias de las librerías y ajustarlos a los cambios importantes cuando lanza una nueva versión.
|
||||
|
||||
### Add schematics
|
||||
Para más detalles de cómo se ven y cómo crearlos, visitar.
|
||||
* [Esquemas de autoria](guide/schematics-authoring)
|
||||
* [Esquemas para librerias](guide/schematics-for-libraries)
|
||||
|
||||
An add schematic is typically supplied with a library, so that the library can be added to an existing project with `ng add`.
|
||||
The `add` command uses your package manager to download new dependencies, and invokes an installation script that is implemented as a schematic.
|
||||
### Esquemas de adición
|
||||
|
||||
For example, the [`@angular/material`](https://material.angular.io/guide/schematics) schematic tells the `add` command to install and set up Angular Material and theming, and register new starter components that can be created with `ng generate`.
|
||||
You can look at this one as an example and model for your own add schematic.
|
||||
Un esquema de adición es típicamente suministrado por una librería, por lo que la librería puede ser agregado a un proyecto existente con `ng add`.
|
||||
|
||||
Partner and third party libraries also support the Angular CLI with add schematics.
|
||||
For example, `@ng-bootstrap/schematics` adds [ng-bootstrap](https://ng-bootstrap.github.io/) to an app, and `@clr/angular` installs and sets up [Clarity from VMWare](https://vmware.github.io/clarity/documentation/v1.0/get-started).
|
||||
El comando `add` usa su administrador de paquetes para descargar una nueva dependencia, e invocar una script de instalación que es implementado como un schama.
|
||||
|
||||
An add schematic can also update a project with configuration changes, add additional dependencies (such as polyfills), or scaffold package-specific initialization code.
|
||||
For example, the `@angular/pwa` schematic turns your application into a PWA by adding an app manifest and service worker, and the `@angular/elements` schematic adds the `document-register-element.js` polyfill and dependencies for Angular Elements.
|
||||
Por ejemplo, el esquema [`@angular/material`](https://material.angular.io/guide/schematics) le dice al comando `add` que instale y configure Angular Material junto con un tema, y que registre nuevos componentes que pueden ser creados con `ng generate`.
|
||||
|
||||
### Generation schematics
|
||||
Puedes verlo como un ejemplo y modelo para tu propio esquema de adición.
|
||||
|
||||
Generation schematics are instructions for the `ng generate` command.
|
||||
The documented sub-commands use the default Angular generation schematics, but you can specify a different schematic (in place of a sub-command) to generate an artifact defined in your library.
|
||||
Las librerías de terceros también soportan Angular CLI con esquemas de adición.
|
||||
|
||||
Angular Material, for example, supplies generation schematics for the UI components that it defines.
|
||||
The following command uses one of these schematics to render an Angular Material `<mat-table>` that is pre-configured with a datasource for sorting and pagination.
|
||||
Por ejemplo, `@ng-bootstrap/schematics` agrega [ng-bootstrap](https://ng-bootstrap.github.io/) para una aplicación, y `@clr/angular` instala y configura [Clarity from VMWare](https://clarity.design/get-started/developing/angular/).
|
||||
|
||||
Un esquema de adición también puede actualizar un proyecto con cambios de configuración, agregar dependencias adicionales (así como polyfills), o estructurar código de inicialización específico del paquete.
|
||||
|
||||
Por ejemplo, el esquema `@angular/pwa` convierte tu aplicación en una PWA agregando un archivo manifest y un service worker, y el esquema `@angular/elements` agrega el `document-register-element.js` polyfill y dependencias para Angular Elements.
|
||||
|
||||
### Esquemas de Generación
|
||||
Los esquemas de generación, son instrucciones para el comando `ng generate`.
|
||||
Los sub comandos documentados usan esquemas de generación predeterminados de Angular, pero puedes especificar un esquema diferente (en lugar de un sub comando) para generar un artefacto definido en su librería.
|
||||
|
||||
Angular Material, por ejemplo, proporciona esquemas de generación para el componentes UI que los definen.
|
||||
El siguiente comando usa uno de esos esquemas para renderizar Angular Material `<mat-table>` que es preconfigurado con un datasource para ordenar y paginar.
|
||||
|
||||
<code-example language="bash">
|
||||
ng generate @angular/material:table <component-name>
|
||||
</code-example>
|
||||
|
||||
### Update schematics
|
||||
### Actualizar esquemas
|
||||
|
||||
The `ng update` command can be used to update your workspace's library dependencies. If you supply no options or use the help option, the command examines your workspace and suggests libraries to update.
|
||||
Los comandos `ng update` pueden ser usados para actualizar las dependencias de la librería de tu espacio de trabajo. Si no proporcionas opciones o usas la opción help, el comando examina tu espácio de trabajo y sugiere librerías para actualizar.
|
||||
|
||||
<code-example language="bash">
|
||||
ng update
|
||||
We analyzed your package.json, there are some packages to update:
|
||||
|
||||
Name Version Command to update
|
||||
--------------------------------------------------------------------------------
|
||||
@angular/cdk 7.2.2 -> 7.3.1 ng update @angular/cdk
|
||||
@angular/cli 7.2.3 -> 7.3.0 ng update @angular/cli
|
||||
@angular/core 7.2.2 -> 7.2.3 ng update @angular/core
|
||||
@angular/material 7.2.2 -> 7.3.1 ng update @angular/material
|
||||
rxjs 6.3.3 -> 6.4.0 ng update rxjs
|
||||
|
||||
|
||||
There might be additional packages that are outdated.
|
||||
Run "ng update --all" to try to update all at the same time.
|
||||
Analizamos tu package.json, hay algunos paquetes por actualizar:
|
||||
Name Version Command to update
|
||||
--------------------------------------------------------------------------------
|
||||
@angular/cdk 7.2.2 -> 7.3.1 ng update @angular/cdk
|
||||
@angular/cli 7.2.3 -> 7.3.0 ng update @angular/cli
|
||||
@angular/core 7.2.2 -> 7.2.3 ng update @angular/core
|
||||
@angular/material 7.2.2 -> 7.3.1 ng update @angular/material
|
||||
rxjs 6.3.3 -> 6.4.0 ng update rxjs
|
||||
|
||||
Es posible que haya paquetes adicionales que están actualizados.
|
||||
Ejecutar "ng update --all" trata de actualizar todos los packages al mismo tiempo.
|
||||
</code-example>
|
||||
|
||||
If you pass the command a set of libraries to update (or the `--all` flag), it updates those libraries, their peer dependencies, and the peer dependencies that depend on them.
|
||||
Si le pasas el comando un conjunto de librerías para actualizar (o la bandera `--all`), este actualiza esas librerías, sus dependencias de pares, y las dependencias de pares que dependen de ellos.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
If there are inconsistencies (for example, if peer dependencies cannot be matched by a simple [semver](https://semver.io/) range), the command generates an error and does not change anything in the workspace.
|
||||
Si hay inconsistencias (por ejemplo, si las dependencias de pares no coinciden con un simple rango [semver](https://semver.io/)), el comando genera un error y no cambia nada en el espacio de trabajo.
|
||||
|
||||
We recommend that you do not force an update of all dependencies by default. Try updating specific dependencies first.
|
||||
Nosotros recomendamos que nos se force la actualización de todas la dependencias predeterminadas. Trata actualizando primero dependencias específicas.
|
||||
|
||||
For more about how the `ng update` command works, see [Update Command](https://github.com/angular/angular-cli/blob/master/docs/specifications/update.md).
|
||||
Para más información acerca del como trabaja el comando `ng update`, puedes vistar [Update Command](https://github.com/angular/angular-cli/blob/master/docs/specifications/update.md).
|
||||
|
||||
</div>
|
||||
|
||||
If you create a new version of your library that introduces potential breaking changes, you can provide an *update schematic* to enable the `ng update` command to automatically resolve any such changes in the project being updated.
|
||||
Si creas una nueva versión de tu librería que introduce cambios importantes, puedes proveer un *update schematic* para habilitar el comando `ng update` para automáticamente resolver cualquier cambio en un proyecto que se actualiza.
|
||||
|
||||
For example, suppose you want to update the Angular Material library.
|
||||
Por ejemplo, supón que quieres actualizar la librería Angular Material.
|
||||
|
||||
<code-example language="bash">
|
||||
ng update @angular/material
|
||||
</code-example>
|
||||
|
||||
This command updates both `@angular/material` and its dependency `@angular/cdk` in your workspace's `package.json`.
|
||||
If either package contains an update schematic that covers migration from the existing version to a new version, the command runs that schematic on your workspace.
|
||||
Este comando actualiza ambos `@angular/material` y sus dependencias `@angular/cdk` en tu espacion de trabajo `package.json`.
|
||||
Si alguno de los paquetes contiene un esquema de actualización que cubre la migración de una versión existente hacia una nueva versión, el comando ejecuta ese esquema en su espacio de trabajo.
|
||||
|
84
aio/content/guide/service-worker-intro.en.md
Normal file
84
aio/content/guide/service-worker-intro.en.md
Normal file
@ -0,0 +1,84 @@
|
||||
# Angular service worker introduction
|
||||
|
||||
Service workers augment the traditional web deployment model and empower applications to deliver a user experience with the reliability and performance on par with natively-installed code. Adding a service worker to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) (also known as a PWA).
|
||||
|
||||
At its simplest, a service worker is a script that runs in the web browser and manages caching for an application.
|
||||
|
||||
Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as `fetch`; it also includes resources referenced in HTML and even the initial request to `index.html`. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers.
|
||||
|
||||
Unlike the other scripts that make up an application, such as the Angular app bundle, the service worker is preserved after the user closes the tab. The next time that browser loads the application, the service worker loads first, and can intercept every request for resources to load the application. If the service worker is designed to do so, it can *completely satisfy the loading of the application, without the need for the network*.
|
||||
|
||||
Even across a fast reliable network, round-trip delays can introduce significant latency when loading the application. Using a service worker to reduce dependency on the network can significantly improve the user experience.
|
||||
|
||||
|
||||
## Service workers in Angular
|
||||
|
||||
Angular applications, as single-page applications, are in a prime position to benefit from the advantages of service workers. Starting with version 5.0.0, Angular ships with a service worker implementation. Angular developers can take advantage of this service worker and benefit from the increased reliability and performance it provides, without needing to code against low-level APIs.
|
||||
|
||||
Angular's service worker is designed to optimize the end user experience of using an application over a slow or unreliable network connection, while also minimizing the risks of serving outdated content.
|
||||
|
||||
The Angular service worker's behavior follows that design goal:
|
||||
|
||||
* Caching an application is like installing a native application. The application is cached as one unit, and all files update together.
|
||||
* A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible.
|
||||
* When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code.
|
||||
* Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready.
|
||||
* The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed.
|
||||
|
||||
To support these behaviors, the Angular service worker loads a *manifest* file from the server. The manifest describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed, the contents of the manifest change, informing the service worker that a new version of the application should be downloaded and cached. This manifest is generated from a CLI-generated configuration file called `ngsw-config.json`.
|
||||
|
||||
Installing the Angular service worker is as simple as including an `NgModule`. In addition to registering the Angular service worker with the browser, this also makes a few services available for injection which interact with the service worker and can be used to control it. For example, an application can ask to be notified when a new update becomes available, or an application can ask the service worker to check the server for available updates.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
To make use of all the features of Angular service worker, use the latest versions of Angular and the Angular CLI.
|
||||
|
||||
In order for service workers to be registered, the app must be accessed over HTTPS, not HTTP.
|
||||
Browsers ignore service workers on pages that are served over an insecure connection.
|
||||
The reason is that service workers are quite powerful, so extra care needs to be taken to ensure the service worker script has not been tampered with.
|
||||
|
||||
There is one exception to this rule: to make local development easier, browsers do _not_ require a secure connection when accessing an app on `localhost`.
|
||||
|
||||
### Browser support
|
||||
|
||||
To benefit from the Angular service worker, your app must run in a web browser that supports service workers in general.
|
||||
Currently, service workers are supported in the latest versions of Chrome, Firefox, Edge, Safari, Opera, UC Browser (Android version) and Samsung Internet.
|
||||
Browsers like IE and Opera Mini do not support service workers.
|
||||
|
||||
If the user is accessing your app via a browser that does not support service workers, the service worker is not registered and related behavior such as offline cache management and push notifications does not happen.
|
||||
More specifically:
|
||||
|
||||
* The browser does not download the service worker script and `ngsw.json` manifest file.
|
||||
* Active attempts to interact with the service worker, such as calling `SwUpdate.checkForUpdate()`, return rejected promises.
|
||||
* The observable events of related services, such as `SwUpdate.available`, are not triggered.
|
||||
|
||||
It is highly recommended that you ensure that your app works even without service worker support in the browser.
|
||||
Although an unsupported browser ignores service worker caching, it will still report errors if the app attempts to interact with the service worker.
|
||||
For example, calling `SwUpdate.checkForUpdate()` will return rejected promises.
|
||||
To avoid such an error, you can check whether the Angular service worker is enabled using `SwUpdate.isEnabled()`.
|
||||
|
||||
To learn more about other browsers that are service worker ready, see the [Can I Use](https://caniuse.com/#feat=serviceworkers) page and [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
|
||||
|
||||
|
||||
## Related resources
|
||||
|
||||
The rest of the articles in this section specifically address the Angular implementation of service workers.
|
||||
|
||||
* [App Shell](guide/app-shell)
|
||||
* [Service Worker Communication](guide/service-worker-communications)
|
||||
* [Service Worker in Production](guide/service-worker-devops)
|
||||
* [Service Worker Configuration](guide/service-worker-config)
|
||||
|
||||
For more information about service workers in general, see [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/).
|
||||
|
||||
For more information about browser support, see the [browser support](https://developers.google.com/web/fundamentals/primers/service-workers/#browser_support) section of [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/), Jake Archibald's [Is Serviceworker ready?](https://jakearchibald.github.io/isserviceworkerready/), and
|
||||
[Can I Use](http://caniuse.com/#feat=serviceworkers).
|
||||
|
||||
For additional recommendations and examples, see:
|
||||
|
||||
* [Precaching with Angular Service Worker](https://web.dev/precaching-with-the-angular-service-worker/)
|
||||
* [Creating a PWA with Angular CLI](https://web.dev/creating-pwa-with-angular-cli/)
|
||||
|
||||
## Next steps
|
||||
|
||||
To begin using Angular service workers, see [Getting Started with service workers](guide/service-worker-getting-started).
|
@ -1,84 +1,84 @@
|
||||
# Angular service worker introduction
|
||||
# Introducción al Service Worker de Angular
|
||||
|
||||
Service workers augment the traditional web deployment model and empower applications to deliver a user experience with the reliability and performance on par with natively-installed code. Adding a service worker to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) (also known as a PWA).
|
||||
Los service Workers amplían el modelo de implementación web tradicional y permiten que las aplicaciones brinden una experiencia de usuario con la confiabilidad y el rendimiento a la par del código instalado de forma nativa. Agregar un service worker a una aplicación Angular es uno de los pasos para convertir una aplicación en una [Aplicación web progresiva] (https://developers.google.com/web/progressive-web-apps/) (también conocida como PWA ).
|
||||
|
||||
At its simplest, a service worker is a script that runs in the web browser and manages caching for an application.
|
||||
En su forma más simple, un service worker es un script que se ejecuta en el navegador web y administra el almacenamiento en caché de una aplicación.
|
||||
|
||||
Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as `fetch`; it also includes resources referenced in HTML and even the initial request to `index.html`. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers.
|
||||
Los service workers funcionan como un proxy de red. Interceptan todas las solicitudes HTTP salientes realizadas por la aplicación y pueden elegir cómo responderlas. Por ejemplo, pueden consultar un caché local y entregar una respuesta en caché si hay una disponible. El proxy no se limita a las solicitudes realizadas a través de código para consumir API, como "fetch"; también incluye recursos referenciados en HTML e incluso la solicitud inicial a `index.html`. El almacenamiento en caché basado en service workers es, por lo tanto, completamente programable y no depende de los encabezados de almacenamiento en caché especificados por el servidor.
|
||||
|
||||
Unlike the other scripts that make up an application, such as the Angular app bundle, the service worker is preserved after the user closes the tab. The next time that browser loads the application, the service worker loads first, and can intercept every request for resources to load the application. If the service worker is designed to do so, it can *completely satisfy the loading of the application, without the need for the network*.
|
||||
A diferencia de los otros scripts que componen una aplicación, como el paquete de la aplicación Angular, el service worker se conserva después de que el usuario cierre la pestaña. La próxima vez que el navegador cargue la aplicación, el service worker cargará primero y podrá interceptar cada solicitud de recursos para cargar la aplicación. Si el service worker está diseñado para hacerlo, puede *satisfacer completamente la carga de la aplicación, sin necesidad de la red*.
|
||||
|
||||
Even across a fast reliable network, round-trip delays can introduce significant latency when loading the application. Using a service worker to reduce dependency on the network can significantly improve the user experience.
|
||||
Incluso en una red rápida y fiable, los retrasos de ida y vuelta pueden introducir una latencia significativa al cargar la aplicación. El uso de un service worker para reducir la dependencia de la red puede mejorar significativamente la experiencia del usuario.
|
||||
|
||||
|
||||
## Service workers in Angular
|
||||
## Service workers en Angular
|
||||
|
||||
Angular applications, as single-page applications, are in a prime position to benefit from the advantages of service workers. Starting with version 5.0.0, Angular ships with a service worker implementation. Angular developers can take advantage of this service worker and benefit from the increased reliability and performance it provides, without needing to code against low-level APIs.
|
||||
Las aplicaciones de Angular, como aplicaciones de una sola página, están en una posición privilegiada para beneficiarse de las ventajas de los service workers. A partir de la versión 5.0.0, Angular se envía con una implementación del service worker. Los desarrolladores de Angular pueden aprovechar este service worker y beneficiarse de la mayor fiabilidad y rendimiento que proporciona, sin necesidad de codificar con APIs de bajo nivel.
|
||||
|
||||
Angular's service worker is designed to optimize the end user experience of using an application over a slow or unreliable network connection, while also minimizing the risks of serving outdated content.
|
||||
El service worker de Angular está diseñado para optimizar la experiencia del usuario final al usar una aplicación en una conexión de red lenta o poco fiable, al mismo tiempo que minimiza los riesgos de ofrecer contenido desactualizado.
|
||||
|
||||
The Angular service worker's behavior follows that design goal:
|
||||
El comportamiento del service worker de Angular sigue ese objetivo de diseño:
|
||||
|
||||
* Caching an application is like installing a native application. The application is cached as one unit, and all files update together.
|
||||
* A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible.
|
||||
* When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code.
|
||||
* Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready.
|
||||
* The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed.
|
||||
* El almacenamiento en caché de una aplicación es como instalar una aplicación nativa. La aplicación se almacena en caché como una unidad y todos los archivos se actualizan juntos.
|
||||
* Una aplicación en ejecución continúa ejecutándose con la misma versión de todos los archivos. No comienza a recibir repentinamente archivos en caché de una versión más reciente, que probablemente sean incompatibles.
|
||||
* Cuando los usuarios actualizan la aplicación, ven la última versión completamente almacenada en caché. Las pestañas nuevas cargan el último código almacenado en caché.
|
||||
* Las actualizaciones ocurren en segundo plano, relativamente rápido después de que se publican los cambios. La versión anterior de la aplicación se sirve hasta que se instala y está lista una actualización.
|
||||
* El service worker conserva el ancho de banda cuando es posible. Los recursos solo se descargan si han cambiado.
|
||||
|
||||
To support these behaviors, the Angular service worker loads a *manifest* file from the server. The manifest describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed, the contents of the manifest change, informing the service worker that a new version of the application should be downloaded and cached. This manifest is generated from a CLI-generated configuration file called `ngsw-config.json`.
|
||||
Para admitir estos comportamientos, el service worker de Angular carga un archivo * manifiesto * desde el servidor. El manifiesto describe los recursos para almacenar en caché e incluye hashes del contenido de cada archivo. Cuando se implementa una actualización de la aplicación, el contenido del manifiesto cambia e informa al service worker que se debe descargar y almacenar en caché una nueva versión de la aplicación. Este manifiesto se genera a partir de un archivo de configuración generado por CLI llamado `ngsw-config.json`.
|
||||
|
||||
Installing the Angular service worker is as simple as including an `NgModule`. In addition to registering the Angular service worker with the browser, this also makes a few services available for injection which interact with the service worker and can be used to control it. For example, an application can ask to be notified when a new update becomes available, or an application can ask the service worker to check the server for available updates.
|
||||
Instalar el service worker de Angular es tan simple como incluir un `NgModule`. Además de registrar el service worker de Angular en el navegador, esto también hace que algunos servicios estén disponibles para inyección que interactúan con el service worker y se pueden usar para controlarlo. Por ejemplo, una aplicación puede solicitar que se le notifique cuando esté disponible una nueva actualización, o una aplicación puede pedirle al service worker que busque actualizaciones disponibles en el servidor.
|
||||
|
||||
## Prerequisites
|
||||
## Requisitos previos
|
||||
|
||||
To make use of all the features of Angular service worker, use the latest versions of Angular and the Angular CLI.
|
||||
Para hacer uso de todas las características del Angular service worker, use las últimas versiones de Angular y Angular CLI.
|
||||
|
||||
In order for service workers to be registered, the app must be accessed over HTTPS, not HTTP.
|
||||
Browsers ignore service workers on pages that are served over an insecure connection.
|
||||
The reason is that service workers are quite powerful, so extra care needs to be taken to ensure the service worker script has not been tampered with.
|
||||
Para que los service workers se registren, se debe acceder a la aplicación a través de HTTPS, no de HTTP.
|
||||
Los navegadores ignoran a los service workers en las páginas que se sirven a través de una conexión insegura.
|
||||
La razón es que los service workers son bastante poderosos, por lo que se debe tener especial cuidado para garantizar que el script del service worker no se haya alterado.
|
||||
|
||||
There is one exception to this rule: to make local development easier, browsers do _not_ require a secure connection when accessing an app on `localhost`.
|
||||
Hay una excepción a esta regla: para facilitar el desarrollo local, los navegadores _no_ requieren una conexión segura al acceder a una aplicación en `localhost`.
|
||||
|
||||
### Browser support
|
||||
### Soporte de navegador
|
||||
|
||||
To benefit from the Angular service worker, your app must run in a web browser that supports service workers in general.
|
||||
Currently, service workers are supported in the latest versions of Chrome, Firefox, Edge, Safari, Opera, UC Browser (Android version) and Samsung Internet.
|
||||
Browsers like IE and Opera Mini do not support service workers.
|
||||
Para beneficiarse del service worker de Angular, su aplicación debe ejecutarse en un navegador web que admita service workers en general.
|
||||
Actualmente, los service workers son compatibles con las últimas versiones de Chrome, Firefox, Edge, Safari, Opera, UC Browser (versión de Android) y Samsung Internet.
|
||||
Los navegadores como IE y Opera Mini no son compatibles con los service workers.
|
||||
|
||||
If the user is accessing your app via a browser that does not support service workers, the service worker is not registered and related behavior such as offline cache management and push notifications does not happen.
|
||||
More specifically:
|
||||
Si el usuario accede a su aplicación a través de un navegador que no es compatible con los service workers, el service worker no es registrado y el comportamiento relacionado como la administración de caché sin conexión y las notificaciones automáticas, no ocurre.
|
||||
Más específicamente:
|
||||
|
||||
* The browser does not download the service worker script and `ngsw.json` manifest file.
|
||||
* Active attempts to interact with the service worker, such as calling `SwUpdate.checkForUpdate()`, return rejected promises.
|
||||
* The observable events of related services, such as `SwUpdate.available`, are not triggered.
|
||||
* El navegador no descarga la secuencia de comandos del service worker y el archivo de manifiesto `ngsw.json`.
|
||||
* Intentos activos de interactuar con el service worker, como llamar a `SwUpdate.checkForUpdate ()`, devuelve promesas rechazadas.
|
||||
* Los eventos observables de servicios relacionados, como "SwUpdate.available", no se activan.
|
||||
|
||||
It is highly recommended that you ensure that your app works even without service worker support in the browser.
|
||||
Although an unsupported browser ignores service worker caching, it will still report errors if the app attempts to interact with the service worker.
|
||||
For example, calling `SwUpdate.checkForUpdate()` will return rejected promises.
|
||||
To avoid such an error, you can check whether the Angular service worker is enabled using `SwUpdate.isEnabled()`.
|
||||
Se recomienda encarecidamente que se asegure de que su aplicación funcione incluso sin la asistencia del trabajador de servicio en el navegador.
|
||||
Aunque un navegador no compatible ignora el almacenamiento en caché del service worker, seguirá informando errores si la aplicación intenta interactuar con el service worker.
|
||||
Por ejemplo, llamar a `SwUpdate.checkForUpdate ()` devolverá las promesas rechazadas.
|
||||
Para evitar tal error, puede verificar si el service worker de Angular está habilitado usando `SwUpdate.isEnabled ()`.
|
||||
|
||||
To learn more about other browsers that are service worker ready, see the [Can I Use](https://caniuse.com/#feat=serviceworkers) page and [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
|
||||
Para obtener más información sobre otros navegadores que soportan service workers, consulta [Can I Use](https://caniuse.com/#feat=serviceworkers) y [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
|
||||
|
||||
|
||||
## Related resources
|
||||
## Recursos Relacionados
|
||||
|
||||
The rest of the articles in this section specifically address the Angular implementation of service workers.
|
||||
El resto de los artículos de esta sección abordan específicamente la implementación de los service workers en Angular.
|
||||
|
||||
* [App Shell](guide/app-shell)
|
||||
* [Service Worker Communication](guide/service-worker-communications)
|
||||
* [Service Worker in Production](guide/service-worker-devops)
|
||||
* [Service Worker Configuration](guide/service-worker-config)
|
||||
* [Comunicación del Service Worker](guide/service-worker-communications)
|
||||
* [Service Worker en producción](guide/service-worker-devops)
|
||||
* [Service Worker Configuración](guide/service-worker-config)
|
||||
|
||||
For more information about service workers in general, see [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/).
|
||||
Para obtener más información sobre los service workers en general, consulta [Service Workers: una Introducción](https://developers.google.com/web/fundamentals/primers/service-workers/).
|
||||
|
||||
For more information about browser support, see the [browser support](https://developers.google.com/web/fundamentals/primers/service-workers/#browser_support) section of [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/), Jake Archibald's [Is Serviceworker ready?](https://jakearchibald.github.io/isserviceworkerready/), and
|
||||
Para obtener más información sobre la compatibilidad con el navegador, consulta la [soporte del navegador](https://developers.google.com/web/fundamentals/primers/service-workers/#browser_support) sección de [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers/), [Is Serviceworker ready?](https://jakearchibald.github.io/isserviceworkerready/) Jake Archibald, y
|
||||
[Can I Use](http://caniuse.com/#feat=serviceworkers).
|
||||
|
||||
For additional recommendations and examples, see:
|
||||
Para obtener recomendaciones y ejemplos adicionales, consulta:
|
||||
|
||||
* [Precaching with Angular Service Worker](https://web.dev/precaching-with-the-angular-service-worker/)
|
||||
* [Creating a PWA with Angular CLI](https://web.dev/creating-pwa-with-angular-cli/)
|
||||
* [Precaching con Angular Service Worker](https://web.dev/precaching-with-the-angular-service-worker/)
|
||||
* [Creando una PWA con Angular CLI](https://web.dev/creating-pwa-with-angular-cli/)
|
||||
|
||||
## Next steps
|
||||
## Siguientes pasos con el Angular CLI
|
||||
|
||||
To begin using Angular service workers, see [Getting Started with service workers](guide/service-worker-getting-started).
|
||||
Comienza a usar los service workers en Angular, consulta [Introducción a los trabajadores del servicio](guide/service-worker-getting-started).
|
||||
|
74
aio/content/guide/set-document-title.en.md
Normal file
74
aio/content/guide/set-document-title.en.md
Normal file
@ -0,0 +1,74 @@
|
||||
{@a top}
|
||||
|
||||
# Set the document title
|
||||
|
||||
Your app should be able to make the browser title bar say whatever you want it to say.
|
||||
This cookbook explains how to do it.
|
||||
|
||||
See the <live-example name="set-document-title"></live-example>.
|
||||
|
||||
## The problem with *<title>*
|
||||
|
||||
The obvious approach is to bind a property of the component to the HTML `<title>` like this:
|
||||
|
||||
<code-example format=''>
|
||||
<title>{{This_Does_Not_Work}}</title>
|
||||
</code-example>
|
||||
|
||||
Sorry but that won't work.
|
||||
The root component of the application is an element contained within the `<body>` tag.
|
||||
The HTML `<title>` is in the document `<head>`, outside the body, making it inaccessible to Angular data binding.
|
||||
|
||||
You could grab the browser `document` object and set the title manually.
|
||||
That's dirty and undermines your chances of running the app outside of a browser someday.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Running your app outside a browser means that you can take advantage of server-side
|
||||
pre-rendering for near-instant first app render times and for SEO. It means you could run from
|
||||
inside a Web Worker to improve your app's responsiveness by using multiple threads. And it
|
||||
means that you could run your app inside Electron.js or Windows Universal to deliver it to the desktop.
|
||||
|
||||
</div>
|
||||
|
||||
## Use the `Title` service
|
||||
|
||||
Fortunately, Angular bridges the gap by providing a `Title` service as part of the *Browser platform*.
|
||||
The [Title](api/platform-browser/Title) service is a simple class that provides an API
|
||||
for getting and setting the current HTML document title:
|
||||
|
||||
* `getTitle() : string`—Gets the title of the current HTML document.
|
||||
* `setTitle( newTitle : string )`—Sets the title of the current HTML document.
|
||||
|
||||
You can inject the `Title` service into the root `AppComponent` and expose a bindable `setTitle` method that calls it:
|
||||
|
||||
|
||||
<code-example path="set-document-title/src/app/app.component.ts" region="class" header="src/app/app.component.ts (class)"></code-example>
|
||||
|
||||
Bind that method to three anchor tags and voilà!
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/set-document-title/set-title-anim.gif" alt="Set title">
|
||||
</div>
|
||||
|
||||
Here's the complete solution:
|
||||
|
||||
<code-tabs>
|
||||
<code-pane header="src/main.ts" path="set-document-title/src/main.ts"></code-pane>
|
||||
<code-pane header="src/app/app.module.ts" path="set-document-title/src/app/app.module.ts"></code-pane>
|
||||
<code-pane header="src/app/app.component.ts" path="set-document-title/src/app/app.component.ts"></code-pane>
|
||||
</code-tabs>
|
||||
|
||||
## Why provide the `Title` service in `bootstrap`
|
||||
|
||||
Generally you want to provide application-wide services in the root application component, `AppComponent`.
|
||||
|
||||
This cookbook recommends registering the title service during bootstrapping,
|
||||
a location you reserve for configuring the runtime Angular environment.
|
||||
|
||||
That's exactly what you're doing.
|
||||
The `Title` service is part of the Angular *browser platform*.
|
||||
If you bootstrap your application into a different platform,
|
||||
you'll have to provide a different `Title` service that understands
|
||||
the concept of a "document title" for that specific platform.
|
||||
Ideally, the application itself neither knows nor cares about the runtime environment.
|
@ -1,57 +1,54 @@
|
||||
{@a top}
|
||||
|
||||
# Set the document title
|
||||
# Establecer el título del documento
|
||||
|
||||
Your app should be able to make the browser title bar say whatever you want it to say.
|
||||
This cookbook explains how to do it.
|
||||
Tu aplicación debería poder hacer que el título de la barra del navegador diga lo que quieras que diga.
|
||||
Esta guía explica cómo hacerlo.
|
||||
|
||||
See the <live-example name="set-document-title"></live-example>.
|
||||
Ve el <live-example name="set-document-title"></live-example>.
|
||||
|
||||
## The problem with *<title>*
|
||||
## El problema con el *<título>*
|
||||
|
||||
The obvious approach is to bind a property of the component to the HTML `<title>` like this:
|
||||
La manera mas obvia es enlazar una propiedad del componente al HTML `<title>` como este:
|
||||
|
||||
<code-example format=''>
|
||||
<title>{{This_Does_Not_Work}}</title>
|
||||
<title>{{Esto_No_Funciona}}</title>
|
||||
</code-example>
|
||||
|
||||
Sorry but that won't work.
|
||||
The root component of the application is an element contained within the `<body>` tag.
|
||||
The HTML `<title>` is in the document `<head>`, outside the body, making it inaccessible to Angular data binding.
|
||||
Lamentablemente eso no funcionará. El componente raíz de la aplicación es un elemento contenido en la etiqueta `<body>`. El `<title>` HTML está en el `<head>` del documento, fuera del `<body>`, lo que lo hace inaccesible para el enlace de datos de Angular.
|
||||
|
||||
You could grab the browser `document` object and set the title manually.
|
||||
That's dirty and undermines your chances of running the app outside of a browser someday.
|
||||
Tu podrías tomar el objeto `document` del navegador y establecer el título manualmente.
|
||||
Eso no es ideal y socava tus posibilidades de ejecutar la aplicación fuera de un navegador algún día.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Running your app outside a browser means that you can take advantage of server-side
|
||||
pre-rendering for near-instant first app render times and for SEO. It means you could run from
|
||||
inside a Web Worker to improve your app's responsiveness by using multiple threads. And it
|
||||
means that you could run your app inside Electron.js or Windows Universal to deliver it to the desktop.
|
||||
Ejecutar tu aplicación fuera de un navegador significa que puedes aprovechar las ventajas del renderizado del lado del servidor
|
||||
para tiempos del primer renderizado de la primera aplicación casi instantáneos y para SEO. Significa que puedes correr la aplicación
|
||||
dentro de un Web Worker para mejorar la capacidad de respuesta de tu aplicación mediante el uso de varios subprocesos. Y también
|
||||
significa que puedes ejecutar tu aplicación dentro de Electron.js o Windows Universal para enviarla al escritorio.
|
||||
|
||||
</div>
|
||||
|
||||
## Use the `Title` service
|
||||
## Utiliza el servicio `Title`
|
||||
|
||||
Fortunately, Angular bridges the gap by providing a `Title` service as part of the *Browser platform*.
|
||||
The [Title](api/platform-browser/Title) service is a simple class that provides an API
|
||||
for getting and setting the current HTML document title:
|
||||
Afortunadamente, Angular reduce las diferencias al proporcionar un servicio `Title` como parte de la *plataforma del navegador*.
|
||||
El servicio [Title](api/platform-browser/Title) es una clase simple que proporciona un API
|
||||
para obtener y configurar el título del documento HTML actual:
|
||||
|
||||
* `getTitle() : string`—Gets the title of the current HTML document.
|
||||
* `setTitle( newTitle : string )`—Sets the title of the current HTML document.
|
||||
|
||||
You can inject the `Title` service into the root `AppComponent` and expose a bindable `setTitle` method that calls it:
|
||||
* `getTitle() : string`—Obtiene el título del documento HTML actual.
|
||||
* `setTitle( newTitle : string )`—Establece el título del documento HTML actual.
|
||||
|
||||
Puedes inyectar el servicio `Title` en la raíz de `AppComponent` y exponer un método `setTitle` enlazable que lo llame:
|
||||
|
||||
<code-example path="set-document-title/src/app/app.component.ts" region="class" header="src/app/app.component.ts (class)"></code-example>
|
||||
|
||||
Bind that method to three anchor tags and voilà!
|
||||
¡Enlaza ese método a tres etiquetas de anclaje y listo!
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/set-document-title/set-title-anim.gif" alt="Set title">
|
||||
</div>
|
||||
|
||||
Here's the complete solution:
|
||||
Aquí está la solución completa:
|
||||
|
||||
<code-tabs>
|
||||
<code-pane header="src/main.ts" path="set-document-title/src/main.ts"></code-pane>
|
||||
@ -59,16 +56,16 @@ Here's the complete solution:
|
||||
<code-pane header="src/app/app.component.ts" path="set-document-title/src/app/app.component.ts"></code-pane>
|
||||
</code-tabs>
|
||||
|
||||
## Why provide the `Title` service in `bootstrap`
|
||||
## ¿Por qué proporcionar el servicio `Title` en el `arranque`?
|
||||
|
||||
Generally you want to provide application-wide services in the root application component, `AppComponent`.
|
||||
Por lo general, deseas proporcionar servicios para toda la aplicación en el componente de la aplicación raíz, `AppComponent`.
|
||||
|
||||
This cookbook recommends registering the title service during bootstrapping,
|
||||
a location you reserve for configuring the runtime Angular environment.
|
||||
Esta guía recomienda registrar el servicio de títulos durante el arranque (boostrapping),
|
||||
una ubicación que se reserva para configurar el ambiente de ejecución de Angular.
|
||||
|
||||
That's exactly what you're doing.
|
||||
The `Title` service is part of the Angular *browser platform*.
|
||||
If you bootstrap your application into a different platform,
|
||||
you'll have to provide a different `Title` service that understands
|
||||
the concept of a "document title" for that specific platform.
|
||||
Ideally, the application itself neither knows nor cares about the runtime environment.
|
||||
Eso es exactamente lo que está haciendo.
|
||||
El servicio `Title` es parte de la *plataforma del navegador* de Angular.
|
||||
Si inicias tu aplicación en una plataforma diferente,
|
||||
tendrás que proporcionar un servicio de `Title` diferente que comprenda
|
||||
el concepto de un "título de documento" para esa plataforma específica.
|
||||
Idealmente, la aplicación en sí no conoce ni se preocupa por el ambiente de ejecución.
|
||||
|
132
aio/content/guide/setup-local.en.md
Normal file
132
aio/content/guide/setup-local.en.md
Normal file
@ -0,0 +1,132 @@
|
||||
# Setting up the local environment and workspace
|
||||
|
||||
|
||||
This guide explains how to set up your environment for Angular development using the [Angular CLI tool](cli "CLI command reference").
|
||||
It includes information about prerequisites, installing the CLI, creating an initial workspace and starter app, and running that app locally to verify your setup.
|
||||
|
||||
|
||||
<div class="callout is-helpful">
|
||||
<header>Try Angular without local setup</header>
|
||||
|
||||
If you are new to Angular, you might want to start with [Try it now!](start), which introduces the essentials of Angular in the context of a ready-made basic online store app that you can examine and modify. This standalone tutorial takes advantage of the interactive [StackBlitz](https://stackblitz.com/) environment for online development. You don't need to set up your local environment until you're ready.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
{@a devenv}
|
||||
{@a prerequisites}
|
||||
## Prerequisites
|
||||
|
||||
To use the Angular framework, you should be familiar with the following:
|
||||
|
||||
* [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
||||
* [HTML](https://developer.mozilla.org/docs/Learn/HTML/Introduction_to_HTML)
|
||||
* [CSS](https://developer.mozilla.org/docs/Learn/CSS/First_steps)
|
||||
|
||||
Knowledge of [TypeScript](https://www.typescriptlang.org/) is helpful, but not required.
|
||||
|
||||
To install Angular on your local system, you need the following:
|
||||
|
||||
{@a nodejs}
|
||||
|
||||
* **Node.js**
|
||||
|
||||
Angular requires a [current, active LTS, or maintenance LTS](https://nodejs.org/about/releases) version of Node.js.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For information about specific version requirements, see the `engines` key in the [package.json](https://unpkg.com/@angular/cli/package.json) file.
|
||||
|
||||
</div>
|
||||
|
||||
For more information on installing Node.js, see [nodejs.org](http://nodejs.org "Nodejs.org").
|
||||
If you are unsure what version of Node.js runs on your system, run `node -v` in a terminal window.
|
||||
|
||||
{@a npm}
|
||||
|
||||
* **npm package manager**
|
||||
|
||||
Angular, the Angular CLI, and Angular applications depend on [npm packages](https://docs.npmjs.com/getting-started/what-is-npm) for many features and functions.
|
||||
To download and install npm packages, you need an npm package manager.
|
||||
This guide uses the [npm client](https://docs.npmjs.com/cli/install) command line interface, which is installed with `Node.js` by default.
|
||||
To check that you have the npm client installed, run `npm -v` in a terminal window.
|
||||
|
||||
|
||||
{@a install-cli}
|
||||
|
||||
## Install the Angular CLI
|
||||
|
||||
You use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
|
||||
|
||||
To install the Angular CLI, open a terminal window and run the following command:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
npm install -g @angular/cli
|
||||
</code-example>
|
||||
|
||||
{@a create-proj}
|
||||
|
||||
## Create a workspace and initial application
|
||||
|
||||
You develop apps in the context of an Angular [**workspace**](guide/glossary#workspace).
|
||||
|
||||
To create a new workspace and initial starter app:
|
||||
|
||||
1. Run the CLI command `ng new` and provide the name `my-app`, as shown here:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
ng new my-app
|
||||
|
||||
</code-example>
|
||||
|
||||
2. The `ng new` command prompts you for information about features to include in the initial app. Accept the defaults by pressing the Enter or Return key.
|
||||
|
||||
The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few minutes.
|
||||
|
||||
The CLI creates a new workspace and a simple Welcome app, ready to run.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You also have the option to use Angular's strict mode, which can help you write better, more maintainable code.
|
||||
For more information, see [Strict mode](/guide/strict-mode).
|
||||
|
||||
</div>
|
||||
|
||||
{@a serve}
|
||||
|
||||
## Run the application
|
||||
|
||||
The Angular CLI includes a server, so that you can build and serve your app locally.
|
||||
|
||||
1. Navigate to the workspace folder, such as `my-app`.
|
||||
|
||||
1. Run the following command:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
cd my-app
|
||||
ng serve --open
|
||||
</code-example>
|
||||
|
||||
The `ng serve` command launches the server, watches your files,
|
||||
and rebuilds the app as you make changes to those files.
|
||||
|
||||
The `--open` (or just `-o`) option automatically opens your browser
|
||||
to `http://localhost:4200/`.
|
||||
|
||||
If your installation and setup was successful, you should see a page similar to the following.
|
||||
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/setup-local/app-works.png' alt="Welcome to my-app!">
|
||||
</div>
|
||||
|
||||
|
||||
## Next steps
|
||||
|
||||
* For a more thorough introduction to the fundamental concepts and terminology of Angular single-page app architecture and design principles, read the [Angular Concepts](guide/architecture) section.
|
||||
|
||||
* Work through the [Tour of Heroes Tutorial](tutorial), a complete hands-on exercise that introduces you to the app development process using the Angular CLI and walks through important subsystems.
|
||||
|
||||
* To learn more about using the Angular CLI, see the [CLI Overview](cli "CLI Overview"). In addition to creating the initial workspace and app scaffolding, you can use the CLI to generate Angular code such as components and services. The CLI supports the full development cycle, including building, testing, bundling, and deployment.
|
||||
|
||||
* For more information about the Angular files generated by `ng new`, see [Workspace and Project File Structure](guide/file-structure).
|
@ -1,64 +1,64 @@
|
||||
# Setting up the local environment and workspace
|
||||
# Configurar el ambiente y el espacio de trabajo locales
|
||||
|
||||
|
||||
This guide explains how to set up your environment for Angular development using the [Angular CLI tool](cli "CLI command reference").
|
||||
It includes information about prerequisites, installing the CLI, creating an initial workspace and starter app, and running that app locally to verify your setup.
|
||||
Esta guía explica cómo configurar tu ambiente para el desarrollo Angular usando la [Herramienta CLI de Angular](cli "CLI command reference").
|
||||
Incluye información sobre los requisitos previos, la instalación de la CLI, la creación de un espacio de trabajo inicial y una aplicación de inicio, y la ejecución de esa aplicación localmente para verificar su configuración.
|
||||
|
||||
|
||||
<div class="callout is-helpful">
|
||||
<header>Try Angular without local setup</header>
|
||||
<header>Prueba Angular sin configuración local</header>
|
||||
|
||||
If you are new to Angular, you might want to start with [Try it now!](start), which introduces the essentials of Angular in the context of a ready-made basic online store app that you can examine and modify. This standalone tutorial takes advantage of the interactive [StackBlitz](https://stackblitz.com/) environment for online development. You don't need to set up your local environment until you're ready.
|
||||
Si eres nuevo en Angular, quizás quieras comenzar con [¡Pruébalo ahora!](start), que presenta los aspectos esenciales de Angular en el contexto de una aplicación de tienda en línea básica lista para usar que puedes examinar y modificar. Este tutorial independiente aprovecha lo interactivo del ambiente [StackBlitz](https://stackblitz.com/) para el desarrollo online. No es necesario que configures tu entorno local hasta que estés listo.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
{@a devenv}
|
||||
{@a prerequisites}
|
||||
## Prerequisites
|
||||
## Prerrequisitos
|
||||
|
||||
To use the Angular framework, you should be familiar with the following:
|
||||
Para usar el framewok Angular, debes estar familiarizado con lo siguiente:
|
||||
|
||||
* [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
|
||||
* [HTML](https://developer.mozilla.org/docs/Learn/HTML/Introduction_to_HTML)
|
||||
* [CSS](https://developer.mozilla.org/docs/Learn/CSS/First_steps)
|
||||
|
||||
Knowledge of [TypeScript](https://www.typescriptlang.org/) is helpful, but not required.
|
||||
Conocimiento de [TypeScript](https://www.typescriptlang.org/) es útil, pero no obligatorio.
|
||||
|
||||
To install Angular on your local system, you need the following:
|
||||
Para instalar Angular en tu sistema local, necesitas lo siguiente:
|
||||
|
||||
{@a nodejs}
|
||||
|
||||
* **Node.js**
|
||||
|
||||
Angular requires a [current, active LTS, or maintenance LTS](https://nodejs.org/about/releases) version of Node.js.
|
||||
Angular requiere una versión [actual, LTS activa o LTS de mantenimiento](https://nodejs.org/about/releases) de Node.js.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For information about specific version requirements, see the `engines` key in the [package.json](https://unpkg.com/@angular/cli/package.json) file.
|
||||
Para obtener información sobre los requisitos específicos de la versión, consulta la llave `engines` en el archivo [package.json](https://unpkg.com/@angular/cli/package.json).
|
||||
|
||||
</div>
|
||||
|
||||
For more information on installing Node.js, see [nodejs.org](http://nodejs.org "Nodejs.org").
|
||||
If you are unsure what version of Node.js runs on your system, run `node -v` in a terminal window.
|
||||
Para obtener más información sobre la instalación de Node.js, consulta [nodejs.org](http://nodejs.org "Nodejs.org").
|
||||
Si no estás seguro de qué versión de Node.js se ejecuta en tu sistema, ejecuta `node -v` en una terminal.
|
||||
|
||||
{@a npm}
|
||||
|
||||
* **npm package manager**
|
||||
|
||||
Angular, the Angular CLI, and Angular applications depend on [npm packages](https://docs.npmjs.com/getting-started/what-is-npm) for many features and functions.
|
||||
To download and install npm packages, you need an npm package manager.
|
||||
This guide uses the [npm client](https://docs.npmjs.com/cli/install) command line interface, which is installed with `Node.js` by default.
|
||||
To check that you have the npm client installed, run `npm -v` in a terminal window.
|
||||
Angular, CLI de Angular, y las aplicaciones de Angular dependen de [paquetes npm](https://docs.npmjs.com/getting-started/what-is-npm) para muchas funcionalidades y funciones.
|
||||
Para descargar e instalar paquetes npm, necesitas un administrador de paquetes npm.
|
||||
Esta guía utiliza la interfaz de línea de comandos del [cliente npm](https://docs.npmjs.com/cli/install), que se instala con `Node.js` por defecto.
|
||||
Para comprobar que tienes instalado el cliente npm, ejecuta `npm -v` en una terminal.
|
||||
|
||||
|
||||
{@a install-cli}
|
||||
|
||||
## Install the Angular CLI
|
||||
## Instalar la CLI de Angular
|
||||
|
||||
You use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
|
||||
Utilizarás la CLI de Angular para crear proyectos, generar código de aplicaciones y bibliotecas, y realizar una variedad de tareas de desarrollo, como pruebas, agrupación e implementación.
|
||||
|
||||
To install the Angular CLI, open a terminal window and run the following command:
|
||||
Para instalar CLI de Angular, abre una terminal y ejecuta el siguiente comando:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
npm install -g @angular/cli
|
||||
@ -66,54 +66,54 @@ To install the Angular CLI, open a terminal window and run the following command
|
||||
|
||||
{@a create-proj}
|
||||
|
||||
## Create a workspace and initial application
|
||||
## Crea un espacio de trabajo y una aplicación inicial
|
||||
|
||||
You develop apps in the context of an Angular [**workspace**](guide/glossary#workspace).
|
||||
Desarrollas aplicaciones en el contexto de un [**espacio de trabajo**](guide/glossary#workspace) de Angular.
|
||||
|
||||
To create a new workspace and initial starter app:
|
||||
Para crear un nuevo espacio de trabajo y una aplicación inicial:
|
||||
|
||||
1. Run the CLI command `ng new` and provide the name `my-app`, as shown here:
|
||||
1. Ejecuta el comando CLI `ng new` y proporciona el nombre `my-app`, como se muestra aquí:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
ng new my-app
|
||||
|
||||
</code-example>
|
||||
|
||||
2. The `ng new` command prompts you for information about features to include in the initial app. Accept the defaults by pressing the Enter or Return key.
|
||||
2. El comando `ng new` te solicitará información sobre las funciones que debe incluir en la aplicación inicial. Acepta los valores predeterminados presionando la tecla Enter o Return.
|
||||
|
||||
The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few minutes.
|
||||
La CLI de Angular instala los paquetes npm de Angular necesarios y otras dependencias. Esto puede tardar unos minutos.
|
||||
|
||||
The CLI creates a new workspace and a simple Welcome app, ready to run.
|
||||
La CLI crea un nuevo espacio de trabajo y una aplicación de bienvenida simple, lista para ejecutarse.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You also have the option to use Angular's strict mode, which can help you write better, more maintainable code.
|
||||
For more information, see [Strict mode](/guide/strict-mode).
|
||||
También tienes la opción de usar el modo estricto de Angular, que puede ayudarte a escribir un mejor código y más fácil de mantener.
|
||||
Para más información, mira [Modo estricto](/guide/strict-mode).
|
||||
|
||||
</div>
|
||||
|
||||
{@a serve}
|
||||
|
||||
## Run the application
|
||||
## Ejecutar la aplicación
|
||||
|
||||
The Angular CLI includes a server, so that you can build and serve your app locally.
|
||||
La CLI de Angular incluye un servidor, de modo que puede crear y servir su aplicación localmente.
|
||||
|
||||
1. Navigate to the workspace folder, such as `my-app`.
|
||||
1. Navega a la carpeta del espacio de trabajo, como `my-app`.
|
||||
|
||||
1. Run the following command:
|
||||
1. Ejecuta el siguiente comando:
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
cd my-app
|
||||
ng serve --open
|
||||
</code-example>
|
||||
|
||||
The `ng serve` command launches the server, watches your files,
|
||||
and rebuilds the app as you make changes to those files.
|
||||
El comando `ng serve` inicia el servidor, observa tus archivos,
|
||||
y reconstruye la aplicación a medida que realizas cambios en esos archivos.
|
||||
|
||||
The `--open` (or just `-o`) option automatically opens your browser
|
||||
to `http://localhost:4200/`.
|
||||
La opción `--open` (o simplemente` -o`) abre automáticamente tu navegador
|
||||
en `http://localhost:4200/`.
|
||||
|
||||
If your installation and setup was successful, you should see a page similar to the following.
|
||||
Si tu instalación y configuración fue exitosa, deberías ver una página similar a la siguiente.
|
||||
|
||||
|
||||
<div class="lightbox">
|
||||
@ -121,12 +121,12 @@ If your installation and setup was successful, you should see a page similar to
|
||||
</div>
|
||||
|
||||
|
||||
## Next steps
|
||||
## Pasos siguientes
|
||||
|
||||
* For a more thorough introduction to the fundamental concepts and terminology of Angular single-page app architecture and design principles, read the [Angular Concepts](guide/architecture) section.
|
||||
* Para obtener una introducción más completa a los conceptos fundamentales y la terminología de la arquitectura de aplicaciones de una sola página y los principios de diseño de Angular, lee la sección [Conceptos Angular](guide/architecture) .
|
||||
|
||||
* Work through the [Tour of Heroes Tutorial](tutorial), a complete hands-on exercise that introduces you to the app development process using the Angular CLI and walks through important subsystems.
|
||||
* Trabaja en el [Tutorial de Tour de los Héroes](tutorial), un ejercicio práctico completo que te presenta el proceso de desarrollo de aplicaciones mediante la CLI de Angular y te explica los subsistemas importantes.
|
||||
|
||||
* To learn more about using the Angular CLI, see the [CLI Overview](cli "CLI Overview"). In addition to creating the initial workspace and app scaffolding, you can use the CLI to generate Angular code such as components and services. The CLI supports the full development cycle, including building, testing, bundling, and deployment.
|
||||
* Para obtener más información sobre el uso de la CLI de Angular, consulta la [Descripción general del CLI](cli "CLI Overview"). Además de crear el espacio de trabajo inicial y andamios de la aplicación, puedes usar la CLI para generar código de Angular como componentes y servicios. La CLI soporta el ciclo de desarrollo completo, incluida la creación, las pruebas, la agrupación y la implementación.
|
||||
|
||||
* For more information about the Angular files generated by `ng new`, see [Workspace and Project File Structure](guide/file-structure).
|
||||
* Para obtener más información sobre los archivos de Angular generados por `ng new`, consulta [Espacio de trabajo y Estructura de archivos del proyecto](guide/file-structure).
|
||||
|
62
aio/content/guide/sharing-ngmodules.en.md
Normal file
62
aio/content/guide/sharing-ngmodules.en.md
Normal file
@ -0,0 +1,62 @@
|
||||
# Sharing modules
|
||||
|
||||
Creating shared modules allows you to organize and streamline your code. You can put commonly
|
||||
used directives, pipes, and components into one module and then import just that module wherever
|
||||
you need it in other parts of your app.
|
||||
|
||||
Consider the following module from an imaginary app:
|
||||
|
||||
|
||||
```typescript
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { CustomerComponent } from './customer.component';
|
||||
import { NewItemDirective } from './new-item.directive';
|
||||
import { OrdersPipe } from './orders.pipe';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule ],
|
||||
declarations: [ CustomerComponent, NewItemDirective, OrdersPipe ],
|
||||
exports: [ CustomerComponent, NewItemDirective, OrdersPipe,
|
||||
CommonModule, FormsModule ]
|
||||
})
|
||||
export class SharedModule { }
|
||||
```
|
||||
|
||||
Note the following:
|
||||
|
||||
* It imports the `CommonModule` because the module's component needs common directives.
|
||||
* It declares and exports the utility pipe, directive, and component classes.
|
||||
* It re-exports the `CommonModule` and `FormsModule`.
|
||||
|
||||
By re-exporting `CommonModule` and `FormsModule`, any other module that imports this
|
||||
`SharedModule`, gets access to directives like `NgIf` and `NgFor` from `CommonModule`
|
||||
and can bind to component properties with `[(ngModel)]`, a directive in the `FormsModule`.
|
||||
|
||||
Even though the components declared by `SharedModule` might not bind
|
||||
with `[(ngModel)]` and there may be no need for `SharedModule`
|
||||
to import `FormsModule`, `SharedModule` can still export
|
||||
`FormsModule` without listing it among its `imports`. This
|
||||
way, you can give other modules access to `FormsModule` without
|
||||
having to import it directly into the `@NgModule` decorator.
|
||||
|
||||
### Using components vs services from other modules
|
||||
|
||||
There is an important distinction between using another module's component and
|
||||
using a service from another module. Import modules when you want to use
|
||||
directives, pipes, and components. Importing a module with services means that you will have a new instance of that service, which typically is not what you need (typically one wants to reuse an existing service). Use module imports to control service instantiation.
|
||||
|
||||
The most common way to get a hold of shared services is through Angular
|
||||
[dependency injection](guide/dependency-injection), rather than through the module system (importing a module will result in a new service instance, which is not a typical usage).
|
||||
|
||||
To read about sharing services, see [Providers](guide/providers).
|
||||
|
||||
|
||||
<hr />
|
||||
|
||||
## More on NgModules
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Providers](guide/providers).
|
||||
* [Types of Feature Modules](guide/module-types).
|
@ -1,10 +1,8 @@
|
||||
# Sharing modules
|
||||
# Compartiendo módulos
|
||||
|
||||
Creating shared modules allows you to organize and streamline your code. You can put commonly
|
||||
used directives, pipes, and components into one module and then import just that module wherever
|
||||
you need it in other parts of your app.
|
||||
La creación de módulos compartidos te permite organizar y optimizar tu código. Puedes colocar directivas, `pipes`, y componentes de uso común en un módulo y despues importar solo ese módulo donde lo necesites en otras partes de tu aplicación.
|
||||
|
||||
Consider the following module from an imaginary app:
|
||||
Considera el siguiente módulo de una aplicación imaginaria:
|
||||
|
||||
|
||||
```typescript
|
||||
@ -24,39 +22,33 @@ import { OrdersPipe } from './orders.pipe';
|
||||
export class SharedModule { }
|
||||
```
|
||||
|
||||
Note the following:
|
||||
Ten en cuenta lo siguiente:
|
||||
|
||||
* It imports the `CommonModule` because the module's component needs common directives.
|
||||
* It declares and exports the utility pipe, directive, and component classes.
|
||||
* It re-exports the `CommonModule` and `FormsModule`.
|
||||
* Esto importa `CommonModule` porque el componente del módulo necesita directivas comunes.
|
||||
* Declara y exporta las clases de componentes, directivas y `pipes`
|
||||
* Esto reexporta `CommonModule` y `FormsModule`.
|
||||
|
||||
By re-exporting `CommonModule` and `FormsModule`, any other module that imports this
|
||||
`SharedModule`, gets access to directives like `NgIf` and `NgFor` from `CommonModule`
|
||||
and can bind to component properties with `[(ngModel)]`, a directive in the `FormsModule`.
|
||||
Al reexportar `CommonModule` y `FormsModule`, cualquier otro módulo que importe este
|
||||
`SharedModule`, obtiene acceso a directivas como `NgIf` y `NgFor` desde `CommonModule`
|
||||
y puede vincularse a las propiedades del componente con `[(ngModel)]`, a una directiva en `FormsModule`.
|
||||
|
||||
Even though the components declared by `SharedModule` might not bind
|
||||
with `[(ngModel)]` and there may be no need for `SharedModule`
|
||||
to import `FormsModule`, `SharedModule` can still export
|
||||
`FormsModule` without listing it among its `imports`. This
|
||||
way, you can give other modules access to `FormsModule` without
|
||||
having to import it directly into the `@NgModule` decorator.
|
||||
Aunque los componentes declarados por `SharedModule` pueden no vincularse con `[(ngModel)]` y puede que no sea necesario que `SharedModule` importe `FormsModule`, `SharedModule` aún puede exportar
|
||||
`FormsModule` sin incluirlo entre sus `imports (importaciones)`. De esta manera, puedes dar acceso a otros módulos a `FormsModule` sin tener que importarlo directamente al decorador `@NgModule`.
|
||||
|
||||
### Using components vs services from other modules
|
||||
### Uso de componentes vs servicios de otros módulos
|
||||
|
||||
There is an important distinction between using another module's component and
|
||||
using a service from another module. Import modules when you want to use
|
||||
directives, pipes, and components. Importing a module with services means that you will have a new instance of that service, which typically is not what you need (typically one wants to reuse an existing service). Use module imports to control service instantiation.
|
||||
Existe una distinción importante entre usar el componente de otro módulo y utilizar un servicio de otro módulo. Importa módulos cuando quieras usar directivas, `pipes` y componentes. Importar un módulo con servicios significa que tendrá una nueva instancia de ese servicio, que normalmente no es lo que necesitas (normalmente, quieres reutilizar un servicio existente). Utiliza las importaciones de módulos para controlar la creación de instancias de servicios.
|
||||
|
||||
The most common way to get a hold of shared services is through Angular
|
||||
[dependency injection](guide/dependency-injection), rather than through the module system (importing a module will result in a new service instance, which is not a typical usage).
|
||||
La forma más común de obtener servicios compartidos es através de la
|
||||
[inyección de dependencia](guide/dependency-injection) en Angular, en lugar de a través del sistema del módulo (la importación de un módulo dará como resultado una nueva instancia de servicio, que no es un uso típico).
|
||||
|
||||
To read about sharing services, see [Providers](guide/providers).
|
||||
Para leer acerca de compartir servicios, consulta [Proveedores](guide/providers).
|
||||
|
||||
|
||||
<hr />
|
||||
|
||||
## More on NgModules
|
||||
## Más en NgModules
|
||||
|
||||
You may also be interested in the following:
|
||||
* [Providers](guide/providers).
|
||||
* [Types of Feature Modules](guide/module-types).
|
||||
También te puede interesar lo siguiente:
|
||||
* [Proveedores](guide/providers).
|
||||
* [Tipos de Módulos de funciones](guide/module-types).
|
||||
|
27
aio/content/guide/svg-in-templates.en.md
Normal file
27
aio/content/guide/svg-in-templates.en.md
Normal file
@ -0,0 +1,27 @@
|
||||
# SVG in templates
|
||||
|
||||
It is possible to use SVG as valid templates in Angular. All of the template syntax below is
|
||||
applicable to both SVG and HTML. Learn more in the SVG [1.1](https://www.w3.org/TR/SVG11/) and
|
||||
[2.0](https://www.w3.org/TR/SVG2/) specifications.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example name="template-syntax"></live-example> for a working example containing the code snippets in this guide.
|
||||
|
||||
</div>
|
||||
|
||||
Why would you use SVG as template, instead of simply adding it as image to your application?
|
||||
|
||||
When you use an SVG as the template, you are able to use directives and bindings just like with HTML
|
||||
templates. This means that you will be able to dynamically generate interactive graphics.
|
||||
|
||||
Refer to the sample code snippet below for a syntax example:
|
||||
|
||||
<code-example path="template-syntax/src/app/svg.component.ts" header="src/app/svg.component.ts"></code-example>
|
||||
|
||||
Add the following code to your `svg.component.svg` file:
|
||||
|
||||
<code-example path="template-syntax/src/app/svg.component.svg" header="src/app/svg.component.svg"></code-example>
|
||||
|
||||
Here you can see the use of a `click()` event binding and the property binding syntax
|
||||
(`[attr.fill]="fillColor"`).
|
@ -1,27 +1,21 @@
|
||||
# SVG in templates
|
||||
# SVG en templates
|
||||
|
||||
It is possible to use SVG as valid templates in Angular. All of the template syntax below is
|
||||
applicable to both SVG and HTML. Learn more in the SVG [1.1](https://www.w3.org/TR/SVG11/) and
|
||||
[2.0](https://www.w3.org/TR/SVG2/) specifications.
|
||||
Es posible utilizar SVG como un template válido en Angular. Toda la sintaxis de templates a continuación es aplicable tanto a SVG como a HTML. Puedes consultar más en las especificaciones SVG [1.1](https://www.w3.org/TR/SVG11/) y [2.0](https://www.w3.org/TR/SVG2/) .
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example name="template-syntax"></live-example> for a working example containing the code snippets in this guide.
|
||||
Consulta <live-example name="template-syntax"></live-example> para ver un ejemplo funcional que contiene los fragmentos de código mostrados en esta guía. </div>
|
||||
|
||||
</div>
|
||||
¿Por qué usar un template SVG, cuando puedes simplemente añadirlo como una imagen a tu aplicación?
|
||||
|
||||
Why would you use SVG as template, instead of simply adding it as image to your application?
|
||||
Cuando utilizas SVG como template, puedes emplear directivas y enlaces de la misma forma que harías con templates HTML. Esto significa que puedes generar gráficos interactivos dinámicamente
|
||||
|
||||
When you use an SVG as the template, you are able to use directives and bindings just like with HTML
|
||||
templates. This means that you will be able to dynamically generate interactive graphics.
|
||||
|
||||
Refer to the sample code snippet below for a syntax example:
|
||||
Consulta el fragmento de código proporcionado para un ejemplo de la sintaxis:
|
||||
|
||||
<code-example path="template-syntax/src/app/svg.component.ts" header="src/app/svg.component.ts"></code-example>
|
||||
|
||||
Add the following code to your `svg.component.svg` file:
|
||||
Añade este código a tu archivo`svg.component.svg`:
|
||||
|
||||
<code-example path="template-syntax/src/app/svg.component.svg" header="src/app/svg.component.svg"></code-example>
|
||||
|
||||
Here you can see the use of a `click()` event binding and the property binding syntax
|
||||
(`[attr.fill]="fillColor"`).
|
||||
Aquí puedes ver el uso de un enlace de evento `click()` y la sintaxis de un enlace de propiedad (`[attr.fill]="fillColor"`).
|
||||
|
65
aio/content/guide/template-statements.en.md
Normal file
65
aio/content/guide/template-statements.en.md
Normal file
@ -0,0 +1,65 @@
|
||||
# Template statements
|
||||
|
||||
A template **statement** responds to an **event** raised by a binding target
|
||||
such as an element, component, or directive.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example name="template-syntax">Template syntax</live-example> for
|
||||
the syntax and code snippets in this guide.
|
||||
|
||||
</div>
|
||||
|
||||
The following template statement appears in quotes to the right of the `=` symbol as in `(event)="statement"`.
|
||||
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="context-component-statement" header="src/app/app.component.html"></code-example>
|
||||
|
||||
A template statement *has a side effect*.
|
||||
That's the whole point of an event.
|
||||
It's how you update application state from user action.
|
||||
|
||||
Responding to events is the other side of Angular's "unidirectional data flow".
|
||||
You're free to change anything, anywhere, during this turn of the event loop.
|
||||
|
||||
Like template expressions, template *statements* use a language that looks like JavaScript.
|
||||
The template statement parser differs from the template expression parser and
|
||||
specifically supports both basic assignment (`=`) and chaining expressions with <code>;</code>.
|
||||
|
||||
However, certain JavaScript and template expression syntax is not allowed:
|
||||
|
||||
* <code>new</code>
|
||||
* increment and decrement operators, `++` and `--`
|
||||
* operator assignment, such as `+=` and `-=`
|
||||
* the bitwise operators, such as `|` and `&`
|
||||
* the [pipe operator](guide/template-expression-operators#pipe)
|
||||
|
||||
## Statement context
|
||||
|
||||
As with expressions, statements can refer only to what's in the statement context
|
||||
such as an event handling method of the component instance.
|
||||
|
||||
The *statement context* is typically the component instance.
|
||||
The *deleteHero* in `(click)="deleteHero()"` is a method of the data-bound component.
|
||||
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="context-component-statement" header="src/app/app.component.html"></code-example>
|
||||
|
||||
The statement context may also refer to properties of the template's own context.
|
||||
In the following examples, the template `$event` object,
|
||||
a [template input variable](guide/built-in-directives#template-input-variable) (`let hero`),
|
||||
and a [template reference variable](guide/template-reference-variables) (`#heroForm`)
|
||||
are passed to an event handling method of the component.
|
||||
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="context-var-statement" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Template context names take precedence over component context names.
|
||||
In `deleteHero(hero)` above, the `hero` is the template input variable,
|
||||
not the component's `hero` property.
|
||||
|
||||
## Statement guidelines
|
||||
|
||||
Template statements cannot refer to anything in the global namespace. They
|
||||
can't refer to `window` or `document`.
|
||||
They can't call `console.log` or `Math.max`.
|
||||
|
||||
As with expressions, avoid writing complex template statements.
|
||||
A method call or simple property assignment should be the norm.
|
@ -1,65 +1,70 @@
|
||||
# Template statements
|
||||
# Declaraciones de plantilla
|
||||
|
||||
A template **statement** responds to an **event** raised by a binding target
|
||||
such as an element, component, or directive.
|
||||
Una **declaración** de plantilla responde a un **evento** provocado por un enlace a un objetivo
|
||||
como un elemento, componente o directiva.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example name="template-syntax">Template syntax</live-example> for
|
||||
the syntax and code snippets in this guide.
|
||||
Mira la <live-example name="template-syntax">sintaxis de la plantilla</live-example> para
|
||||
la sintaxis y los fragmentos de código de esta guía.
|
||||
|
||||
</div>
|
||||
|
||||
The following template statement appears in quotes to the right of the `=` symbol as in `(event)="statement"`.
|
||||
La siguiente declaración de plantilla aparece entre comillas a la derecha del símbolo `=` como en `(event)="statement"`.
|
||||
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="context-component-statement" header="src/app/app.component.html"></code-example>
|
||||
|
||||
A template statement *has a side effect*.
|
||||
That's the whole point of an event.
|
||||
It's how you update application state from user action.
|
||||
Una declaración de plantilla *tiene un efecto secundario*.
|
||||
Ese es el objetivo de un evento.
|
||||
Es la forma de actualizar el estado de la aplicación a partir de la acción del usuario.
|
||||
|
||||
Responding to events is the other side of Angular's "unidirectional data flow".
|
||||
You're free to change anything, anywhere, during this turn of the event loop.
|
||||
|
||||
Like template expressions, template *statements* use a language that looks like JavaScript.
|
||||
The template statement parser differs from the template expression parser and
|
||||
specifically supports both basic assignment (`=`) and chaining expressions with <code>;</code>.
|
||||
<div class="alert is-helpful">
|
||||
|
||||
However, certain JavaScript and template expression syntax is not allowed:
|
||||
Responder a los eventos es un aspecto del [flujo de datos unidireccional](guide/glossary#unidirectional-data-flow) de Angular.
|
||||
|
||||
</div>
|
||||
Eres libre de cambiar cualquier cosa, en cualquier lugar, durante este ciclo del evento.
|
||||
|
||||
Al igual que las expresiones de plantilla, las *declaraciones* de plantilla utilizan un lenguaje que se parece a JavaScript.
|
||||
El analizador de declaraciones de plantilla difiere del analizador de expresiones de plantilla y
|
||||
admite específicamente tanto la asignación básica (`=`) como el encadenamiento de expresiones con <code>;</code>.
|
||||
|
||||
Sin embargo, no se permiten determinadas sintaxis de expresión de plantilla y JavaScript:
|
||||
|
||||
* <code>new</code>
|
||||
* increment and decrement operators, `++` and `--`
|
||||
* operator assignment, such as `+=` and `-=`
|
||||
* the bitwise operators, such as `|` and `&`
|
||||
* the [pipe operator](guide/template-expression-operators#pipe)
|
||||
* Operadores de incremento y decremento, `++` y `--`
|
||||
* operador de asignación , como `+=` y `-=`
|
||||
* los operadores bit a bit, como `|` y `&`
|
||||
* el [operador pipe](guide/template-expression-operators#pipe)
|
||||
|
||||
## Statement context
|
||||
## Contexto de la declaración
|
||||
|
||||
As with expressions, statements can refer only to what's in the statement context
|
||||
such as an event handling method of the component instance.
|
||||
Al igual que con las expresiones, las declaraciones solo pueden ver lo que está en el contexto de la declaración
|
||||
como un método de manejo de eventos de la instancia del componente.
|
||||
|
||||
The *statement context* is typically the component instance.
|
||||
The *deleteHero* in `(click)="deleteHero()"` is a method of the data-bound component.
|
||||
El *contexto de la declaración* es típicamente la instancia del componente.
|
||||
El *deleteHero* en `(click)="deleteHero()"` es un método del componente enlazado a datos.
|
||||
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="context-component-statement" header="src/app/app.component.html"></code-example>
|
||||
|
||||
The statement context may also refer to properties of the template's own context.
|
||||
In the following examples, the template `$event` object,
|
||||
a [template input variable](guide/built-in-directives#template-input-variable) (`let hero`),
|
||||
and a [template reference variable](guide/template-reference-variables) (`#heroForm`)
|
||||
are passed to an event handling method of the component.
|
||||
El contexto de la declaración también puede ver las propiedades del propio contexto de la plantilla.
|
||||
En los siguientes ejemplos, el objeto de plantilla `$event`,
|
||||
una [variable de entrada de plantilla](guide/built-in-directives#template-input-variable) (`let hero`),
|
||||
y una [variable de referencia de plantilla](guide/template-reference-variables) (`#heroForm`)
|
||||
se pasan a un método de manejo de eventos del componente.
|
||||
|
||||
<code-example path="template-syntax/src/app/app.component.html" region="context-var-statement" header="src/app/app.component.html"></code-example>
|
||||
|
||||
Template context names take precedence over component context names.
|
||||
In `deleteHero(hero)` above, the `hero` is the template input variable,
|
||||
not the component's `hero` property.
|
||||
Los nombres de contexto de plantilla tienen prioridad sobre los nombres de contexto de componentes.
|
||||
En `deleteHero(hero)` anterior, el `hero` es la variable de entrada de la plantilla
|
||||
no la propiedad `hero` del componente.
|
||||
|
||||
## Statement guidelines
|
||||
## Pautas de la declaración
|
||||
|
||||
Template statements cannot refer to anything in the global namespace. They
|
||||
can't refer to `window` or `document`.
|
||||
They can't call `console.log` or `Math.max`.
|
||||
Las declaraciones de plantilla no pueden ver nada en el espacio de nombres global. No
|
||||
pueden ver `window` o `document`.
|
||||
No pueden llamar `console.log` o `Math.max`.
|
||||
|
||||
As with expressions, avoid writing complex template statements.
|
||||
A method call or simple property assignment should be the norm.
|
||||
Al igual que con las expresiones, evita escribir declaraciones de plantilla complejas.
|
||||
Una llamada a un método o una simple asignación de propiedad debería ser la norma.
|
||||
|
73
aio/content/guide/template-syntax.en.md
Normal file
73
aio/content/guide/template-syntax.en.md
Normal file
@ -0,0 +1,73 @@
|
||||
# Template syntax
|
||||
|
||||
In Angular, a *template* is a chunk of HTML.
|
||||
Within a template, you can use special syntax to leverage many of Angular's features.
|
||||
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before learning template syntax, you should be familiar with the following:
|
||||
|
||||
* [Angular concepts](guide/architecture)
|
||||
* JavaScript
|
||||
* HTML
|
||||
* CSS
|
||||
|
||||
|
||||
<!-- Do we still need the following section? It seems more relevant to those coming from AngularJS, which is now 7 versions ago. -->
|
||||
<!-- You may be familiar with the component/template duality from your experience with model-view-controller (MVC) or model-view-viewmodel (MVVM).
|
||||
In Angular, the component plays the part of the controller/viewmodel, and the template represents the view. -->
|
||||
|
||||
<hr />
|
||||
|
||||
Each Angular template in your app is a section of HTML that you can include as a part of the page that the browser displays.
|
||||
An Angular HTML template renders a view, or user interface, in the browser, just like regular HTML, but with a lot more functionality.
|
||||
|
||||
When you generate an Angular app with the Angular CLI, the `app.component.html` file is the default template containing placeholder HTML.
|
||||
|
||||
The template syntax guides show you how you can control the UX/UI by coordinating data between the class and the template.
|
||||
|
||||
<div class="is-helpful alert">
|
||||
|
||||
Most of the Template Syntax guides have dedicated working example apps that demonstrate the individual topic of each guide.
|
||||
To see all of them working together in one app, see the comprehensive <live-example title="Template Syntax Live Code"></live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## Empower your HTML
|
||||
|
||||
With special Angular syntax in your templates, you can extend the HTML vocabulary of your apps.
|
||||
For example, Angular helps you get and set DOM (Document Object Model) values dynamically with features such as built-in template functions, variables, event listening, and data binding.
|
||||
|
||||
Almost all HTML syntax is valid template syntax.
|
||||
However, because an Angular template is part of an overall webpage, and not the entire page, you don't need to include elements such as `<html>`, `<body>`, or `<base>`.
|
||||
You can focus exclusively on the part of the page you are developing.
|
||||
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
To eliminate the risk of script injection attacks, Angular does not support the `<script>` element in templates.
|
||||
Angular ignores the `<script>` tag and outputs a warning to the browser console.
|
||||
For more information, see the [Security](guide/security) page.
|
||||
|
||||
</div>
|
||||
|
||||
<hr />
|
||||
|
||||
## More on template syntax
|
||||
|
||||
You may also be interested in the following:
|
||||
|
||||
* [Interpolation](guide/interpolation)—learn how to use interpolation and expressions in HTML.
|
||||
* [Template statements](guide/template-statements)—respond to events in your templates.
|
||||
* [Binding syntax](guide/binding-syntax)—use binding to coordinate values in your app.
|
||||
* [Property binding](guide/property-binding)—set properties of target elements or directive `@Input()` decorators.
|
||||
* [Attribute, class, and style bindings](guide/attribute-binding)—set the value of attributes, classes, and styles.
|
||||
* [Event binding](guide/event-binding)—listen for events and your HTML.
|
||||
* [Two-way binding](guide/two-way-binding)—share data between a class and its template.
|
||||
* [Built-in directives](guide/built-in-directives)—listen to and modify the behavior and layout of HTML.
|
||||
* [Template reference variables](guide/template-reference-variables)—use special variables to reference a DOM element within a template.
|
||||
* [Inputs and Outputs](guide/inputs-outputs)—share data between the parent context and child directives or components
|
||||
* [Template expression operators](guide/template-expression-operators)—learn about the pipe operator, `|`, and protect against `null` or `undefined` values in your HTML.
|
||||
* [SVG in templates](guide/svg-in-templates)—dynamically generate interactive graphics.
|
@ -1,14 +1,14 @@
|
||||
# Template syntax
|
||||
# Sintaxis de la plantilla
|
||||
|
||||
In Angular, a *template* is a chunk of HTML.
|
||||
Within a template, you can use special syntax to leverage many of Angular's features.
|
||||
En Angular, una *plantilla* es un fragmento de HTML.
|
||||
Dentro de una plantilla, puedes usar una sintaxis especial para aprovechar muchas de las características de Angular.
|
||||
|
||||
|
||||
## Prerequisites
|
||||
## Prerrequisitos
|
||||
|
||||
Before learning template syntax, you should be familiar with the following:
|
||||
Antes de aprender la sintaxis de la plantilla, debes estar familiarizado con lo siguiente:
|
||||
|
||||
* [Angular concepts](guide/architecture)
|
||||
* [Conceptos de Angular](guide/architecture)
|
||||
* JavaScript
|
||||
* HTML
|
||||
* CSS
|
||||
@ -20,54 +20,55 @@ In Angular, the component plays the part of the controller/viewmodel, and the te
|
||||
|
||||
<hr />
|
||||
|
||||
Each Angular template in your app is a section of HTML that you can include as a part of the page that the browser displays.
|
||||
An Angular HTML template renders a view, or user interface, in the browser, just like regular HTML, but with a lot more functionality.
|
||||
Cada plantilla Angular de tu aplicación es una sección de HTML que puedes incluir como parte de la página que muestra el navegador.
|
||||
Una plantilla HTML Angular muestra una vista, o interfaz de usuario, en el navegador, como HTML normal, pero con mucha más funcionalidad.
|
||||
|
||||
When you generate an Angular app with the Angular CLI, the `app.component.html` file is the default template containing placeholder HTML.
|
||||
Cuando generas una aplicación Angular con Angular CLI, el archivo `app.component.html` es la plantilla predeterminada que contiene HTML de marcador de posición.
|
||||
|
||||
Las guías de sintaxis de la plantilla te muestran cómo puedes controlar la UX/UI coordinando los datos entre la clase y la plantilla.
|
||||
|
||||
The template syntax guides show you how you can control the UX/UI by coordinating data between the class and the template.
|
||||
|
||||
<div class="is-helpful alert">
|
||||
|
||||
Most of the Template Syntax guides have dedicated working example apps that demonstrate the individual topic of each guide.
|
||||
To see all of them working together in one app, see the comprehensive <live-example title="Template Syntax Live Code"></live-example>.
|
||||
La mayoría de las guías de sintaxis de plantillas tienen aplicaciones de ejemplo de trabajo dedicadas que demuestran el tema individual de cada guía.
|
||||
Para verlos a todos trabajando juntos en una aplicación, consulta al completo<live-example title="Template Syntax Live Code"></live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## Empower your HTML
|
||||
## Potencia tu HTML
|
||||
|
||||
With special Angular syntax in your templates, you can extend the HTML vocabulary of your apps.
|
||||
For example, Angular helps you get and set DOM (Document Object Model) values dynamically with features such as built-in template functions, variables, event listening, and data binding.
|
||||
Con una sintaxis Angular especial en tus plantillas, puedes ampliar el vocabulario HTML de tus aplicaciones.
|
||||
Por ejemplo, Angular te ayuda a obtener y establecer valores DOM (Document Object Model) dinámicamente con características como funciones de plantilla integradas, variables, escucha de eventos y enlace de datos.
|
||||
|
||||
Almost all HTML syntax is valid template syntax.
|
||||
However, because an Angular template is part of an overall webpage, and not the entire page, you don't need to include elements such as `<html>`, `<body>`, or `<base>`.
|
||||
You can focus exclusively on the part of the page you are developing.
|
||||
Casi toda la sintaxis HTML es una sintaxis de plantilla válida.
|
||||
Sin embargo, debido a que una plantilla Angular es parte de una página web general, y no de toda la página, no es necesario incluir elementos como `<html>`, `<body>` o `<base>`.
|
||||
Puedes centrarte exclusivamente en la parte de la página que estás desarrollando.
|
||||
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
To eliminate the risk of script injection attacks, Angular does not support the `<script>` element in templates.
|
||||
Angular ignores the `<script>` tag and outputs a warning to the browser console.
|
||||
For more information, see the [Security](guide/security) page.
|
||||
Para eliminar el riesgo de ataques de inyección de scripts, Angular no admite el elemento `<script>` en las plantillas.
|
||||
Angular ignora la etiqueta `<script>` y envía una advertencia a la consola del navegador.
|
||||
Para obtener más información, consulta la página [Seguridad](guide/security).
|
||||
|
||||
</div>
|
||||
|
||||
<hr />
|
||||
|
||||
## More on template syntax
|
||||
## Más sobre la sintaxis de la plantilla
|
||||
|
||||
You may also be interested in the following:
|
||||
También te puede interesar lo siguiente:
|
||||
|
||||
* [Interpolation](guide/interpolation)—learn how to use interpolation and expressions in HTML.
|
||||
* [Template statements](guide/template-statements)—respond to events in your templates.
|
||||
* [Binding syntax](guide/binding-syntax)—use binding to coordinate values in your app.
|
||||
* [Property binding](guide/property-binding)—set properties of target elements or directive `@Input()` decorators.
|
||||
* [Attribute, class, and style bindings](guide/attribute-binding)—set the value of attributes, classes, and styles.
|
||||
* [Event binding](guide/event-binding)—listen for events and your HTML.
|
||||
* [Two-way binding](guide/two-way-binding)—share data between a class and its template.
|
||||
* [Built-in directives](guide/built-in-directives)—listen to and modify the behavior and layout of HTML.
|
||||
* [Template reference variables](guide/template-reference-variables)—use special variables to reference a DOM element within a template.
|
||||
* [Inputs and Outputs](guide/inputs-outputs)—share data between the parent context and child directives or components
|
||||
* [Template expression operators](guide/template-expression-operators)—learn about the pipe operator, `|`, and protect against `null` or `undefined` values in your HTML.
|
||||
* [SVG in templates](guide/svg-in-templates)—dynamically generate interactive graphics.
|
||||
* [Interpolación](guide/interpolation)—aprende a utilizar la interpolación y las expresiones en HTML.
|
||||
* [Declaraciones de plantilla](guide/template-statements)—responde a eventos en sus plantillas.
|
||||
* [Sintaxis de enlace](guide/binding-syntax)—utiliza el enlace para coordinar valores en su aplicación.
|
||||
* [Vinculación de propiedad](guide/property-binding)—establece las propiedades de los elementos de destino o los decoradores de la directiva `@Input ()`.
|
||||
* [Vinculaciones de atributos, clases y estilos](guide/attribute-binding)—establece el valor de atributos, clases y estilos.
|
||||
* [Enlace de eventos](guide/event-binding)—escucha los eventos y tu HTML.
|
||||
* [Enlace bidireccional](guide/two-way-binding)—comparte datos entre una clase y su plantilla.
|
||||
* [Directivas integradas](guide/built-in-directives)—escucha y modifica el comportamiento y el diseño del HTML.
|
||||
* [Variables de referencia de plantilla](guide/template-reference-variables)—usa variables especiales para hacer referencia a un elemento DOM dentro de una plantilla.
|
||||
* [Entradas y salidas](guide/inputs-outputs)—comparte datos entre el contexto principal y las directivas o componentes secundarios
|
||||
* [Operadores de expresión de plantilla](guide/template-expression-operators)—aprende sobre el operador de tubería, `|`, y protégete contra valores `nulos` o` indefinidos` en tu HTML.
|
||||
* [SVG en plantillas](guide/svg-in-templates)—genera gráficos interactivos de forma dinámica.
|
||||
|
29
aio/content/guide/test-debugging.en.md
Normal file
29
aio/content/guide/test-debugging.en.md
Normal file
@ -0,0 +1,29 @@
|
||||
# Debugging tests
|
||||
|
||||
If your tests aren't working as you expect them to, you can inspect and debug them in the browser.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
Debug specs in the browser in the same way that you debug an application.
|
||||
|
||||
1. Reveal the Karma browser window. See [Set up testing](guide/testing#set-up-testing) if you need help with this step.
|
||||
1. Click the **DEBUG** button; it opens a new browser tab and re-runs the tests.
|
||||
1. Open the browser's “Developer Tools” (`Ctrl-Shift-I` on Windows; `Command-Option-I` in macOS).
|
||||
1. Pick the "sources" section.
|
||||
1. Open the `1st.spec.ts` test file (Control/Command-P, then start typing the name of the file).
|
||||
1. Set a breakpoint in the test.
|
||||
1. Refresh the browser, and it stops at the breakpoint.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/testing/karma-1st-spec-debug.png' alt="Karma debugging">
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
@ -1,28 +1,29 @@
|
||||
# Debugging tests
|
||||
|
||||
If your tests aren't working as you expect them to, you can inspect and debug them in the browser.
|
||||
Si tus tests no están funcionando como esperas, puedes inspeccionarlos y hacer debug en el navegador.
|
||||
|
||||
|
||||
|
||||
<div class="alert is-helpful">
|
||||
Para la aplicación de ejemplo que las guías de testing describe, consulta <live-example name="testing" embedded-style noDownload>app de ejemplo</live-example>.
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
Para las funcionalidades de los tests en las guías de testing, consulta <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
Puedes hacer debug de especificaciones en el navegador de la misma forma que haces debug a una aplicación.
|
||||
|
||||
Debug specs in the browser in the same way that you debug an application.
|
||||
|
||||
1. Reveal the Karma browser window. See [Set up testing](guide/testing#set-up-testing) if you need help with this step.
|
||||
1. Click the **DEBUG** button; it opens a new browser tab and re-runs the tests.
|
||||
1. Open the browser's “Developer Tools” (`Ctrl-Shift-I` on Windows; `Command-Option-I` in macOS).
|
||||
1. Pick the "sources" section.
|
||||
1. Open the `1st.spec.ts` test file (Control/Command-P, then start typing the name of the file).
|
||||
1. Set a breakpoint in the test.
|
||||
1. Refresh the browser, and it stops at the breakpoint.
|
||||
1. Revela la ventana del navegador Karma. Consulta [configuración del testing](guide/testing#set-up-testing) si necesitas ayuda con este paso.
|
||||
1. Haz click en el botón **DEBUG**; abrirá una nueva pestaña en el navegador y volverá a ejecutar los tests.
|
||||
1. Abre las "Herramientas de desarrollador" del navegador (`Ctrl-Shift-I` en Windows; `Command-Option-I` in macOS).
|
||||
1. Selecciona la sección "fuentes".
|
||||
1. Abre el archivo test `1st.spec.ts` (Control/Command-P, luego escribe el nombre del archivo).
|
||||
1. Coloca un breakpoint en el test.
|
||||
1. Actualiza tu navegador, se detendrá en el breakpoint establecido.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/testing/karma-1st-spec-debug.png' alt="Karma debugging">
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
|
78
aio/content/guide/testing-attribute-directives.en.md
Normal file
78
aio/content/guide/testing-attribute-directives.en.md
Normal file
@ -0,0 +1,78 @@
|
||||
|
||||
{@a attribute-directive}
|
||||
|
||||
# Testing Attribute Directives
|
||||
|
||||
An _attribute directive_ modifies the behavior of an element, component or another directive.
|
||||
Its name reflects the way the directive is applied: as an attribute on a host element.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
## Testing the `HighlightDirective`
|
||||
|
||||
The sample application's `HighlightDirective` sets the background color of an element
|
||||
based on either a data bound color or a default color (lightgray).
|
||||
It also sets a custom property of the element (`customProperty`) to `true`
|
||||
for no reason other than to show that it can.
|
||||
|
||||
<code-example path="testing/src/app/shared/highlight.directive.ts" header="app/shared/highlight.directive.ts"></code-example>
|
||||
|
||||
It's used throughout the application, perhaps most simply in the `AboutComponent`:
|
||||
|
||||
<code-example path="testing/src/app/about/about.component.ts" header="app/about/about.component.ts"></code-example>
|
||||
|
||||
Testing the specific use of the `HighlightDirective` within the `AboutComponent` requires only the techniques explored in the ["Nested component tests"](guide/testing-components-scenarios#nested-component-tests) section of [Component testing scenarios](guide/testing-components-scenarios).
|
||||
|
||||
<code-example path="testing/src/app/about/about.component.spec.ts" region="tests" header="app/about/about.component.spec.ts"></code-example>
|
||||
|
||||
However, testing a single use case is unlikely to explore the full range of a directive's capabilities.
|
||||
Finding and testing all components that use the directive is tedious, brittle, and almost as unlikely to afford full coverage.
|
||||
|
||||
_Class-only tests_ might be helpful,
|
||||
but attribute directives like this one tend to manipulate the DOM.
|
||||
Isolated unit tests don't touch the DOM and, therefore,
|
||||
do not inspire confidence in the directive's efficacy.
|
||||
|
||||
A better solution is to create an artificial test component that demonstrates all ways to apply the directive.
|
||||
|
||||
<code-example path="testing/src/app/shared/highlight.directive.spec.ts" region="test-component" header="app/shared/highlight.directive.spec.ts (TestComponent)"></code-example>
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/testing/highlight-directive-spec.png' alt="HighlightDirective spec in action">
|
||||
</div>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The `<input>` case binds the `HighlightDirective` to the name of a color value in the input box.
|
||||
The initial value is the word "cyan" which should be the background color of the input box.
|
||||
|
||||
</div>
|
||||
|
||||
Here are some tests of this component:
|
||||
|
||||
<code-example path="testing/src/app/shared/highlight.directive.spec.ts" region="selected-tests" header="app/shared/highlight.directive.spec.ts (selected tests)"></code-example>
|
||||
|
||||
A few techniques are noteworthy:
|
||||
|
||||
- The `By.directive` predicate is a great way to get the elements that have this directive _when their element types are unknown_.
|
||||
|
||||
- The <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:not">`:not` pseudo-class</a>
|
||||
in `By.css('h2:not([highlight])')` helps find `<h2>` elements that _do not_ have the directive.
|
||||
`By.css('*:not([highlight])')` finds _any_ element that does not have the directive.
|
||||
|
||||
- `DebugElement.styles` affords access to element styles even in the absence of a real browser, thanks to the `DebugElement` abstraction.
|
||||
But feel free to exploit the `nativeElement` when that seems easier or more clear than the abstraction.
|
||||
|
||||
- Angular adds a directive to the injector of the element to which it is applied.
|
||||
The test for the default color uses the injector of the second `<h2>` to get its `HighlightDirective` instance
|
||||
and its `defaultColor`.
|
||||
|
||||
- `DebugElement.properties` affords access to the artificial custom property that is set by the directive.
|
||||
|
||||
<hr>
|
@ -1,45 +1,44 @@
|
||||
|
||||
{@a attribute-directive}
|
||||
|
||||
# Testing Attribute Directives
|
||||
# Probando Directivas de Atributo
|
||||
|
||||
An _attribute directive_ modifies the behavior of an element, component or another directive.
|
||||
Its name reflects the way the directive is applied: as an attribute on a host element.
|
||||
Una _directiva de atributo_ modifica el comportamiento de un elemento, componente u otra directiva.
|
||||
Su nombre refleja la forma en que se aplica la directiva: como un atributo en un elemento anfitrión.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
Para la aplicación de muestra que describen las guías de prueba, visita la <live-example name="testing" embedded-style noDownload>aplicación de muestra</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
Para las funcionalidaddes de las pruebas en las guías de pruebas, visita las <live-example name="testing" stackblitz="specs" noDownload>pruebas</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
## Testing the `HighlightDirective`
|
||||
## Probando la `HighlightDirective`
|
||||
|
||||
The sample application's `HighlightDirective` sets the background color of an element
|
||||
based on either a data bound color or a default color (lightgray).
|
||||
It also sets a custom property of the element (`customProperty`) to `true`
|
||||
for no reason other than to show that it can.
|
||||
La directiva de muestra `HighlightDirective` fija el color de fondo de un elemento basado en un color de referencia o en un color predeterminado (lightgray).
|
||||
También establece una propiedad personalizada del elemento (`customProperty`) a `true`
|
||||
sin otro motivo más que demostrar que puede.
|
||||
|
||||
<code-example path="testing/src/app/shared/highlight.directive.ts" header="app/shared/highlight.directive.ts"></code-example>
|
||||
|
||||
It's used throughout the application, perhaps most simply in the `AboutComponent`:
|
||||
Se usa a lo largo de la aplicación, quizás más sencillamente en el `AboutComponent`:
|
||||
|
||||
<code-example path="testing/src/app/about/about.component.ts" header="app/about/about.component.ts"></code-example>
|
||||
|
||||
Testing the specific use of the `HighlightDirective` within the `AboutComponent` requires only the techniques explored in the ["Nested component tests"](guide/testing-components-scenarios#nested-component-tests) section of [Component testing scenarios](guide/testing-components-scenarios).
|
||||
Probar el uso específico de la `HighlightDirective` dentro del `AboutComponent` sólo requiere las técnicas exploradas en la sección ["Pruebas de componentes anidados"](guide/testing-components-scenarios#nested-component-tests) de [Escenarios de pruebas de componentes](guide/testing-components-scenarios).
|
||||
|
||||
<code-example path="testing/src/app/about/about.component.spec.ts" region="tests" header="app/about/about.component.spec.ts"></code-example>
|
||||
|
||||
However, testing a single use case is unlikely to explore the full range of a directive's capabilities.
|
||||
Finding and testing all components that use the directive is tedious, brittle, and almost as unlikely to afford full coverage.
|
||||
Sin embargo, probar un solo caso de uso es poco probable que explore toda la variedad de las posibilidades de una directiva.
|
||||
Encontrar y probar todos los componentes que utilizan la directiva es tedioso, delicado y casi igual de improbable que permita una cobertura completa.
|
||||
|
||||
_Class-only tests_ might be helpful,
|
||||
but attribute directives like this one tend to manipulate the DOM.
|
||||
Isolated unit tests don't touch the DOM and, therefore,
|
||||
do not inspire confidence in the directive's efficacy.
|
||||
Las _Pruebas de clase exclusivas_ pueden ser de ayuda,
|
||||
pero las directivas de atributo como ésta tienden a manipular el DOM.
|
||||
Las pruebas unitarias aisladas no tocan el DOM y, por lo tanto,
|
||||
no inspiran confianza en la eficacia de la directiva.
|
||||
|
||||
A better solution is to create an artificial test component that demonstrates all ways to apply the directive.
|
||||
Una solución mejor es crear un componente de prueba artificial que demuestre todas las formas de aplicar la directiva.
|
||||
|
||||
<code-example path="testing/src/app/shared/highlight.directive.spec.ts" region="test-component" header="app/shared/highlight.directive.spec.ts (TestComponent)"></code-example>
|
||||
|
||||
@ -49,30 +48,30 @@ A better solution is to create an artificial test component that demonstrates al
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The `<input>` case binds the `HighlightDirective` to the name of a color value in the input box.
|
||||
The initial value is the word "cyan" which should be the background color of the input box.
|
||||
El caso de `<input>` vincula la `HighlightDirective` al nombre de un valor de color en el campo de entrada.
|
||||
El valor inicial es la palabra "cyan" que debería ser el color de fondo del cuadro de entrada.
|
||||
|
||||
</div>
|
||||
|
||||
Here are some tests of this component:
|
||||
Aquí hay algunas pruebas de este componente:
|
||||
|
||||
<code-example path="testing/src/app/shared/highlight.directive.spec.ts" region="selected-tests" header="app/shared/highlight.directive.spec.ts (selected tests)"></code-example>
|
||||
|
||||
A few techniques are noteworthy:
|
||||
Cabe destacar algunas técnicas:
|
||||
|
||||
- The `By.directive` predicate is a great way to get the elements that have this directive _when their element types are unknown_.
|
||||
- El predicado de la `By.directive` es una buena forma de obtener los elementos que tienen esta directiva _cuando sus tipos de elementos son desconocidos_.
|
||||
|
||||
- The <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:not">`:not` pseudo-class</a>
|
||||
in `By.css('h2:not([highlight])')` helps find `<h2>` elements that _do not_ have the directive.
|
||||
`By.css('*:not([highlight])')` finds _any_ element that does not have the directive.
|
||||
- La <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:not">`:not` pseudo-clase</a>
|
||||
en `By.css('h2:not([highlight])')` ayuda a encontrar los elementos `<h2>` _que no_ tienen la directiva.
|
||||
`By.css('*:not([highlight])')` encuentra _cualquier_ elemento que no tiene la directiva.
|
||||
|
||||
- `DebugElement.styles` affords access to element styles even in the absence of a real browser, thanks to the `DebugElement` abstraction.
|
||||
But feel free to exploit the `nativeElement` when that seems easier or more clear than the abstraction.
|
||||
- `DebugElement.styles` permite acceder a los estilos de los elementos incluso en ausencia de un navegador real, gracias a la abstracción de `DebugElement`.
|
||||
Pero siéntete libre de explotar el `nativeElement` cuando te parezca más fácil o más claro que la abstracción.
|
||||
|
||||
- Angular adds a directive to the injector of the element to which it is applied.
|
||||
The test for the default color uses the injector of the second `<h2>` to get its `HighlightDirective` instance
|
||||
and its `defaultColor`.
|
||||
- Angular añade una directiva al inyector del elemento al que se aplica.
|
||||
La prueba para el color por defecto usa el inyector del segundo `<h2>` para obtener la instancia de su `HighlightDirective`
|
||||
y su `defaultColor`.
|
||||
|
||||
- `DebugElement.properties` affords access to the artificial custom property that is set by the directive.
|
||||
- `DebugElement.properties` permite el acceso a la propiedad artificial personalizada que se establece en la directiva.
|
||||
|
||||
<hr>
|
||||
|
57
aio/content/guide/testing-code-coverage.en.md
Normal file
57
aio/content/guide/testing-code-coverage.en.md
Normal file
@ -0,0 +1,57 @@
|
||||
{@a code-coverage}
|
||||
|
||||
# Find out how much code you're testing
|
||||
|
||||
The CLI can run unit tests and create code coverage reports.
|
||||
Code coverage reports show you any parts of your code base that may not be properly tested by your unit tests.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
To generate a coverage report run the following command in the root of your project.
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
ng test --no-watch --code-coverage
|
||||
</code-example>
|
||||
|
||||
When the tests are complete, the command creates a new `/coverage` folder in the project. Open the `index.html` file to see a report with your source code and code coverage values.
|
||||
|
||||
If you want to create code-coverage reports every time you test, you can set the following option in the CLI configuration file, `angular.json`:
|
||||
|
||||
```
|
||||
"test": {
|
||||
"options": {
|
||||
"codeCoverage": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Code coverage enforcement
|
||||
|
||||
The code coverage percentages let you estimate how much of your code is tested.
|
||||
If your team decides on a set minimum amount to be unit tested, you can enforce this minimum with the Angular CLI.
|
||||
|
||||
For example, suppose you want the code base to have a minimum of 80% code coverage.
|
||||
To enable this, open the [Karma](https://karma-runner.github.io) test platform configuration file, `karma.conf.js`, and add the following in the `coverageIstanbulReporter:` key.
|
||||
|
||||
```
|
||||
coverageIstanbulReporter: {
|
||||
reports: [ 'html', 'lcovonly' ],
|
||||
fixWebpackSourcePaths: true,
|
||||
thresholds: {
|
||||
statements: 80,
|
||||
lines: 80,
|
||||
branches: 80,
|
||||
functions: 80
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `thresholds` property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.
|
||||
|
@ -1,28 +1,28 @@
|
||||
{@a code-coverage}
|
||||
|
||||
# Find out how much code you're testing
|
||||
# Descubre cuánto código estás probando
|
||||
|
||||
The CLI can run unit tests and create code coverage reports.
|
||||
Code coverage reports show you any parts of your code base that may not be properly tested by your unit tests.
|
||||
El CLI puede ejecutar tests unitarios y crear informes de la cobertura del codigo por ellos.
|
||||
Los informes de cobertura de código muestran las partes de tu código que pueden no estar siento probadas corretamente por sus test unitarios.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
Para la aplicación de muestra que describen las guías de prueba, visita la <live-example name="testing" embedded-style noDownload>aplicación de muestra</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
Para las características de las pruebas en las guías de pruebas, visita <live-example name="testing" stackblitz="specs" noDownload>pruebas</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
To generate a coverage report run the following command in the root of your project.
|
||||
Para generar un informe de cobertura ejecuta el siguiente comando en la raíz del proyecto.
|
||||
|
||||
<code-example language="sh" class="code-shell">
|
||||
ng test --no-watch --code-coverage
|
||||
</code-example>
|
||||
|
||||
When the tests are complete, the command creates a new `/coverage` folder in the project. Open the `index.html` file to see a report with your source code and code coverage values.
|
||||
Cuando las pruebas terminan, el comando crea una nueva carpeta `/coverage` en el proyecto. Abre el archivo `index.html` para ver un informe con tu código y los valores de cobertura de código.
|
||||
|
||||
If you want to create code-coverage reports every time you test, you can set the following option in the CLI configuration file, `angular.json`:
|
||||
Si quieres crear informes de cobertura de código cada vez que ejecutes los test, puedes configurar la siguiente opción en el archivo de configuración del CLI, `angular.json`:
|
||||
|
||||
```
|
||||
"test": {
|
||||
@ -32,13 +32,13 @@ If you want to create code-coverage reports every time you test, you can set the
|
||||
}
|
||||
```
|
||||
|
||||
## Code coverage enforcement
|
||||
## Imponer la cobertura de código
|
||||
|
||||
The code coverage percentages let you estimate how much of your code is tested.
|
||||
If your team decides on a set minimum amount to be unit tested, you can enforce this minimum with the Angular CLI.
|
||||
Los porcentajes de cobertura de código te permiten estimar cuánto porcentaje de tu código es probado.
|
||||
Si tu equipo decide fijar una cantidad mínima de código para ser probada unitariamente puedes imponer este mínimo con el CLI de Angular.
|
||||
|
||||
For example, suppose you want the code base to have a minimum of 80% code coverage.
|
||||
To enable this, open the [Karma](https://karma-runner.github.io) test platform configuration file, `karma.conf.js`, and add the following in the `coverageIstanbulReporter:` key.
|
||||
Por ejemplo, supongamos que quieres que el código tenga un mínimo de 80% de cobertura de código.
|
||||
Para habilitarlo, abre el archivo de configuración de la plataforma de pruebas de [Karma](https://karma-runner.github.io), `karma.conf.js`, y añada lo siguiente en la clave `coverageIstanbulReporter:`.
|
||||
|
||||
```
|
||||
coverageIstanbulReporter: {
|
||||
@ -53,5 +53,5 @@ coverageIstanbulReporter: {
|
||||
}
|
||||
```
|
||||
|
||||
The `thresholds` property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.
|
||||
La propiedad de los `thresholds` hace que la herramienta aplique un mínimo del 80% de cobertura de código cuando se ejecuten las pruebas unitarias en el proyecto.
|
||||
|
||||
|
41
aio/content/guide/testing-pipes.en.md
Normal file
41
aio/content/guide/testing-pipes.en.md
Normal file
@ -0,0 +1,41 @@
|
||||
# Testing Pipes
|
||||
|
||||
You can test [pipes](guide/pipes) without the Angular testing utilities.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
## Testing the `TitleCasePipe`
|
||||
|
||||
A pipe class has one method, `transform`, that manipulates the input
|
||||
value into a transformed output value.
|
||||
The `transform` implementation rarely interacts with the DOM.
|
||||
Most pipes have no dependence on Angular other than the `@Pipe`
|
||||
metadata and an interface.
|
||||
|
||||
Consider a `TitleCasePipe` that capitalizes the first letter of each word.
|
||||
Here's an implementation with a regular expression.
|
||||
|
||||
<code-example path="testing/src/app/shared/title-case.pipe.ts" header="app/shared/title-case.pipe.ts"></code-example>
|
||||
|
||||
Anything that uses a regular expression is worth testing thoroughly.
|
||||
Use simple Jasmine to explore the expected cases and the edge cases.
|
||||
|
||||
<code-example path="testing/src/app/shared/title-case.pipe.spec.ts" region="excerpt" header="app/shared/title-case.pipe.spec.ts"></code-example>
|
||||
|
||||
{@a write-tests}
|
||||
|
||||
## Writing DOM tests to support a pipe test
|
||||
|
||||
These are tests of the pipe _in isolation_.
|
||||
They can't tell if the `TitleCasePipe` is working properly as applied in the application components.
|
||||
|
||||
Consider adding component tests such as this one:
|
||||
|
||||
<code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="title-case-pipe" header="app/hero/hero-detail.component.spec.ts (pipe test)"></code-example>
|
||||
|
@ -1,41 +1,39 @@
|
||||
# Testing Pipes
|
||||
# Probando los Pipes
|
||||
|
||||
You can test [pipes](guide/pipes) without the Angular testing utilities.
|
||||
Puedes probar los [pipes](guide/pipes) sin las utilidades para pruebas de Angular.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
Para la aplicación de muestra que indican las guías de prueba, visita <live-example name="testing" embedded-style noDownload>la aplicación de prueba</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
Para las pruebas de funcionalidades en las guías de prueba, visita <live-example name="testing" stackblitz="specs" noDownload>pruebas</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
## Testing the `TitleCasePipe`
|
||||
## Probando el `TitleCasePipe`
|
||||
|
||||
A pipe class has one method, `transform`, that manipulates the input
|
||||
value into a transformed output value.
|
||||
The `transform` implementation rarely interacts with the DOM.
|
||||
Most pipes have no dependence on Angular other than the `@Pipe`
|
||||
metadata and an interface.
|
||||
La clase de un pipe contiene un método, `transform`, que manipula el valor de entrada y lo transforma en un valor de salida.
|
||||
La implementación del `transform` rara vez interactúa con el DOM.
|
||||
La mayoría de los pipes no dependen de Angular más allá de los metadatos del `@Pipe` y una interfaz.
|
||||
|
||||
Consider a `TitleCasePipe` that capitalizes the first letter of each word.
|
||||
Here's an implementation with a regular expression.
|
||||
Considera una `TitleCasePipe` que pone en mayúscula la primera letra de cada palabra.
|
||||
Aquí está una implementación con una expresión regular.
|
||||
|
||||
<code-example path="testing/src/app/shared/title-case.pipe.ts" header="app/shared/title-case.pipe.ts"></code-example>
|
||||
|
||||
Anything that uses a regular expression is worth testing thoroughly.
|
||||
Use simple Jasmine to explore the expected cases and the edge cases.
|
||||
Cualquier cosa que use una expresión regular vale la pena probarla a fondo.
|
||||
Simplemente usa Jasmine para explorar todos los casos esperados y todos los casos extremos.
|
||||
|
||||
<code-example path="testing/src/app/shared/title-case.pipe.spec.ts" region="excerpt" header="app/shared/title-case.pipe.spec.ts"></code-example>
|
||||
|
||||
{@a write-tests}
|
||||
|
||||
## Writing DOM tests to support a pipe test
|
||||
## Escribiendo pruebas DOM para soportar una prueba de un pipe
|
||||
|
||||
These are tests of the pipe _in isolation_.
|
||||
They can't tell if the `TitleCasePipe` is working properly as applied in the application components.
|
||||
Estas son pruebas de un pipe _en aislamiento_.
|
||||
No pueden decir si el `TitleCasePipe` está funcionando correctamente tal y como se aplica en los componentes de la aplicación.
|
||||
|
||||
Consider adding component tests such as this one:
|
||||
Considera añadir pruebas de componente como por ejemplo esta:
|
||||
|
||||
<code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="title-case-pipe" header="app/hero/hero-detail.component.spec.ts (pipe test)"></code-example>
|
||||
|
||||
|
199
aio/content/guide/testing-services.en.md
Normal file
199
aio/content/guide/testing-services.en.md
Normal file
@ -0,0 +1,199 @@
|
||||
# Testing services
|
||||
|
||||
|
||||
To check that your services are working as you intend, you can write tests specifically for them.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
Services are often the easiest files to unit test.
|
||||
Here are some synchronous and asynchronous unit tests of the `ValueService`
|
||||
written without assistance from Angular testing utilities.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.spec.ts" region="ValueService" header="app/demo/demo.spec.ts"></code-example>
|
||||
|
||||
{@a services-with-dependencies}
|
||||
|
||||
## Services with dependencies
|
||||
|
||||
Services often depend on other services that Angular injects into the constructor.
|
||||
In many cases, it's easy to create and _inject_ these dependencies by hand while
|
||||
calling the service's constructor.
|
||||
|
||||
The `MasterService` is a simple example:
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.ts" region="MasterService" header="app/demo/demo.ts"></code-example>
|
||||
|
||||
`MasterService` delegates its only method, `getValue`, to the injected `ValueService`.
|
||||
|
||||
Here are several ways to test it.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.spec.ts" region="MasterService" header="app/demo/demo.spec.ts"></code-example>
|
||||
|
||||
The first test creates a `ValueService` with `new` and passes it to the `MasterService` constructor.
|
||||
|
||||
However, injecting the real service rarely works well as most dependent services are difficult to create and control.
|
||||
|
||||
Instead you can mock the dependency, use a dummy value, or create a
|
||||
[spy](https://jasmine.github.io/2.0/introduction.html#section-Spies)
|
||||
on the pertinent service method.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Prefer spies as they are usually the easiest way to mock services.
|
||||
|
||||
</div>
|
||||
|
||||
These standard testing techniques are great for unit testing services in isolation.
|
||||
|
||||
However, you almost always inject services into application classes using Angular
|
||||
dependency injection and you should have tests that reflect that usage pattern.
|
||||
Angular testing utilities make it easy to investigate how injected services behave.
|
||||
|
||||
## Testing services with the _TestBed_
|
||||
|
||||
Your app relies on Angular [dependency injection (DI)](guide/dependency-injection)
|
||||
to create services.
|
||||
When a service has a dependent service, DI finds or creates that dependent service.
|
||||
And if that dependent service has its own dependencies, DI finds-or-creates them as well.
|
||||
|
||||
As service _consumer_, you don't worry about any of this.
|
||||
You don't worry about the order of constructor arguments or how they're created.
|
||||
|
||||
As a service _tester_, you must at least think about the first level of service dependencies
|
||||
but you _can_ let Angular DI do the service creation and deal with constructor argument order
|
||||
when you use the `TestBed` testing utility to provide and create services.
|
||||
|
||||
{@a testbed}
|
||||
|
||||
## Angular _TestBed_
|
||||
|
||||
The `TestBed` is the most important of the Angular testing utilities.
|
||||
The `TestBed` creates a dynamically-constructed Angular _test_ module that emulates
|
||||
an Angular [@NgModule](guide/ngmodules).
|
||||
|
||||
The `TestBed.configureTestingModule()` method takes a metadata object that can have most of the properties of an [@NgModule](guide/ngmodules).
|
||||
|
||||
To test a service, you set the `providers` metadata property with an
|
||||
array of the services that you'll test or mock.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-before-each" header="app/demo/demo.testbed.spec.ts (provide ValueService in beforeEach)"></code-example>
|
||||
|
||||
Then inject it inside a test by calling `TestBed.inject()` with the service class as the argument.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** `TestBed.get()` was deprecated as of Angular version 9.
|
||||
To help minimize breaking changes, Angular introduces a new function called `TestBed.inject()`, which you should use instead.
|
||||
For information on the removal of `TestBed.get()`,
|
||||
see its entry in the [Deprecations index](guide/deprecations#index).
|
||||
|
||||
</div>
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-inject-it"></code-example>
|
||||
|
||||
Or inside the `beforeEach()` if you prefer to inject the service as part of your setup.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-inject-before-each"> </code-example>
|
||||
|
||||
When testing a service with a dependency, provide the mock in the `providers` array.
|
||||
|
||||
In the following example, the mock is a spy object.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="master-service-before-each"></code-example>
|
||||
|
||||
The test consumes that spy in the same way it did earlier.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="master-service-it">
|
||||
</code-example>
|
||||
|
||||
{@a no-before-each}
|
||||
|
||||
## Testing without _beforeEach()_
|
||||
|
||||
Most test suites in this guide call `beforeEach()` to set the preconditions for each `it()` test
|
||||
and rely on the `TestBed` to create classes and inject services.
|
||||
|
||||
There's another school of testing that never calls `beforeEach()` and prefers to create classes explicitly rather than use the `TestBed`.
|
||||
|
||||
Here's how you might rewrite one of the `MasterService` tests in that style.
|
||||
|
||||
Begin by putting re-usable, preparatory code in a _setup_ function instead of `beforeEach()`.
|
||||
|
||||
<code-example
|
||||
path="testing/src/app/demo/demo.spec.ts"
|
||||
region="no-before-each-setup"
|
||||
header="app/demo/demo.spec.ts (setup)"></code-example>
|
||||
|
||||
The `setup()` function returns an object literal
|
||||
with the variables, such as `masterService`, that a test might reference.
|
||||
You don't define _semi-global_ variables (e.g., `let masterService: MasterService`)
|
||||
in the body of the `describe()`.
|
||||
|
||||
Then each test invokes `setup()` in its first line, before continuing
|
||||
with steps that manipulate the test subject and assert expectations.
|
||||
|
||||
<code-example
|
||||
path="testing/src/app/demo/demo.spec.ts"
|
||||
region="no-before-each-test"></code-example>
|
||||
|
||||
Notice how the test uses
|
||||
[_destructuring assignment_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
|
||||
to extract the setup variables that it needs.
|
||||
|
||||
<code-example
|
||||
path="testing/src/app/demo/demo.spec.ts"
|
||||
region="no-before-each-setup-call">
|
||||
</code-example>
|
||||
|
||||
Many developers feel this approach is cleaner and more explicit than the
|
||||
traditional `beforeEach()` style.
|
||||
|
||||
Although this testing guide follows the traditional style and
|
||||
the default [CLI schematics](https://github.com/angular/angular-cli)
|
||||
generate test files with `beforeEach()` and `TestBed`,
|
||||
feel free to adopt _this alternative approach_ in your own projects.
|
||||
|
||||
## Testing HTTP services
|
||||
|
||||
Data services that make HTTP calls to remote servers typically inject and delegate
|
||||
to the Angular [`HttpClient`](guide/http) service for XHR calls.
|
||||
|
||||
You can test a data service with an injected `HttpClient` spy as you would
|
||||
test any service with a dependency.
|
||||
<code-example
|
||||
path="testing/src/app/model/hero.service.spec.ts"
|
||||
region="test-with-spies"
|
||||
header="app/model/hero.service.spec.ts (tests with spies)">
|
||||
</code-example>
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
The `HeroService` methods return `Observables`. You must
|
||||
_subscribe_ to an observable to (a) cause it to execute and (b)
|
||||
assert that the method succeeds or fails.
|
||||
|
||||
The `subscribe()` method takes a success (`next`) and fail (`error`) callback.
|
||||
Make sure you provide _both_ callbacks so that you capture errors.
|
||||
Neglecting to do so produces an asynchronous uncaught observable error that
|
||||
the test runner will likely attribute to a completely different test.
|
||||
|
||||
</div>
|
||||
|
||||
## _HttpClientTestingModule_
|
||||
|
||||
Extended interactions between a data service and the `HttpClient` can be complex
|
||||
and difficult to mock with spies.
|
||||
|
||||
The `HttpClientTestingModule` can make these testing scenarios more manageable.
|
||||
|
||||
While the _code sample_ accompanying this guide demonstrates `HttpClientTestingModule`,
|
||||
this page defers to the [Http guide](guide/http#testing-http-requests),
|
||||
which covers testing with the `HttpClientTestingModule` in detail.
|
||||
|
@ -1,172 +1,172 @@
|
||||
# Testing services
|
||||
# Probando servicios
|
||||
|
||||
|
||||
To check that your services are working as you intend, you can write tests specifically for them.
|
||||
Para comprobar que tus servicios funcionan como deseas, puedes escribir pruebas específicamente para ellos.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For the sample app that the testing guides describe, see the <live-example name="testing" embedded-style noDownload>sample app</live-example>.
|
||||
Para la aplicación de muestra que describe las guías de prueba, consulta la <live-example name="testing" embedded-style noDownload>aplicación de muestra</live-example>.
|
||||
|
||||
For the tests features in the testing guides, see <live-example name="testing" stackblitz="specs" noDownload>tests</live-example>.
|
||||
Para las funcionalidades de las pruebas en las guías de prueba, consulta las <live-example name="testing" stackblitz="specs" noDownload>pruebas</live-example>.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
Services are often the easiest files to unit test.
|
||||
Here are some synchronous and asynchronous unit tests of the `ValueService`
|
||||
written without assistance from Angular testing utilities.
|
||||
Los servicios suelen ser los archivos en los que es mas fácil realizar pruebas unitarias.
|
||||
Estas son algunas pruebas unitarias sincrónicas y asincrónicas del `ValueService`
|
||||
escritas sin ayuda de las utilidades de prueba Angular.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.spec.ts" region="ValueService" header="app/demo/demo.spec.ts"></code-example>
|
||||
|
||||
{@a services-with-dependencies}
|
||||
|
||||
## Services with dependencies
|
||||
## Servicios con dependencias
|
||||
|
||||
Services often depend on other services that Angular injects into the constructor.
|
||||
In many cases, it's easy to create and _inject_ these dependencies by hand while
|
||||
calling the service's constructor.
|
||||
Los servicios a menudo dependen de otros servicios que Angular inyecta en el constructor.
|
||||
En muchos casos, es fácil crear e _inyectar_ estas dependencias a mano mientras
|
||||
se llama al constructor del servicio.
|
||||
|
||||
The `MasterService` is a simple example:
|
||||
El `MasterService` es un ejemplo simple:
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.ts" region="MasterService" header="app/demo/demo.ts"></code-example>
|
||||
|
||||
`MasterService` delegates its only method, `getValue`, to the injected `ValueService`.
|
||||
`MasterService` delega su único método, `getValue`, al `ValueService` inyectado.
|
||||
|
||||
Here are several ways to test it.
|
||||
Aquí hay varias formas de probarlo.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.spec.ts" region="MasterService" header="app/demo/demo.spec.ts"></code-example>
|
||||
|
||||
The first test creates a `ValueService` with `new` and passes it to the `MasterService` constructor.
|
||||
La primera prueba crea un `ValueService` con `new` y lo pasa al constructor de `MasterService`.
|
||||
|
||||
However, injecting the real service rarely works well as most dependent services are difficult to create and control.
|
||||
Sin embargo, inyectar el servicio real rara vez funciona bien, ya que la mayoría de los servicios dependientes son difíciles de crear y controlar.
|
||||
|
||||
Instead you can mock the dependency, use a dummy value, or create a
|
||||
[spy](https://jasmine.github.io/2.0/introduction.html#section-Spies)
|
||||
on the pertinent service method.
|
||||
En su lugar, puedes hacer un mock de la dependencia, usar un valor ficticio o crear un
|
||||
[espía](https://jasmine.github.io/2.0/introduction.html#section-Spies)
|
||||
sobre el método del servicio pertinente.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Prefer spies as they are usually the easiest way to mock services.
|
||||
Utiliza espías, ya que suelen ser la forma más fácil de hacer mocks a los servicios.
|
||||
|
||||
</div>
|
||||
|
||||
These standard testing techniques are great for unit testing services in isolation.
|
||||
Estas técnicas de prueba estándar son excelentes para hacer pruebas unitarias de servicios de forma aislada.
|
||||
|
||||
However, you almost always inject services into application classes using Angular
|
||||
dependency injection and you should have tests that reflect that usage pattern.
|
||||
Angular testing utilities make it easy to investigate how injected services behave.
|
||||
Sin embargo, casi siempre inyecta servicios en clases de aplicación usando
|
||||
la inyección de dependencias de Angular y debe tener pruebas que reflejen ese patrón de uso.
|
||||
Las utilidades de pruebas de Angular facilitan la investigación de cómo se comportan los servicios inyectados.
|
||||
|
||||
## Testing services with the _TestBed_
|
||||
## Probando los servicios con _TestBed_
|
||||
|
||||
Your app relies on Angular [dependency injection (DI)](guide/dependency-injection)
|
||||
to create services.
|
||||
When a service has a dependent service, DI finds or creates that dependent service.
|
||||
And if that dependent service has its own dependencies, DI finds-or-creates them as well.
|
||||
Tu aplicación se basa en la [inyección de dependencias (ID)](guide/dependency-injection) de Angular
|
||||
para crear servicios.
|
||||
Cuando un servicio tiene un servicio dependiente, la inyección de dependencia busca o crea ese servicio dependiente.
|
||||
Y si ese servicio dependiente tiene sus propias dependencias, la inyección de dependencia también las encuentra o crea.
|
||||
|
||||
As service _consumer_, you don't worry about any of this.
|
||||
You don't worry about the order of constructor arguments or how they're created.
|
||||
Como _consumidor_ de servicios, no te preocupas por nada de esto.
|
||||
No te preocupes por el orden de los argumentos del constructor o cómo se crean.
|
||||
|
||||
As a service _tester_, you must at least think about the first level of service dependencies
|
||||
but you _can_ let Angular DI do the service creation and deal with constructor argument order
|
||||
when you use the `TestBed` testing utility to provide and create services.
|
||||
Como _probador_ de servicios, debes pensar al menos en el primer nivel de dependencias del servicio
|
||||
pero _puedes_ dejar que la inyección de dependencia de Angular haga la creación del servicio y se ocupe del orden de los argumentos del constructor
|
||||
cuando uses la utilidad de prueba `TestBed` para proporcionar y crear servicios.
|
||||
|
||||
{@a testbed}
|
||||
|
||||
## Angular _TestBed_
|
||||
|
||||
The `TestBed` is the most important of the Angular testing utilities.
|
||||
The `TestBed` creates a dynamically-constructed Angular _test_ module that emulates
|
||||
an Angular [@NgModule](guide/ngmodules).
|
||||
El `TestBed` es la más importante de las utilidades de prueba de Angular.
|
||||
El `TestBed` crea un modulo Angular _test_ construido dinámicamente que emula
|
||||
un [@NgModule](guide/ngmodules) de Angular.
|
||||
|
||||
The `TestBed.configureTestingModule()` method takes a metadata object that can have most of the properties of an [@NgModule](guide/ngmodules).
|
||||
El método `TestBed.configureTestingModule()` toma un objeto de metadatos que puede tener la mayoría de las propiedades de un [@NgModule](guide/ngmodules).
|
||||
|
||||
To test a service, you set the `providers` metadata property with an
|
||||
array of the services that you'll test or mock.
|
||||
Para probar un servicio, estableces la propiedad de metadatos de `providers` con un
|
||||
array de los servicios que probarás o simularás.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-before-each" header="app/demo/demo.testbed.spec.ts (provide ValueService in beforeEach)"></code-example>
|
||||
|
||||
Then inject it inside a test by calling `TestBed.inject()` with the service class as the argument.
|
||||
Luego inyéctalo dentro de una prueba llamando `TestBed.inject()` con la clase del servicio como argumento.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**Note:** `TestBed.get()` was deprecated as of Angular version 9.
|
||||
To help minimize breaking changes, Angular introduces a new function called `TestBed.inject()`, which you should use instead.
|
||||
For information on the removal of `TestBed.get()`,
|
||||
see its entry in the [Deprecations index](guide/deprecations#index).
|
||||
**Nota:** `TestBed.get()` quedó obsoleto a partir de la versión 9 de Angular.
|
||||
Para ayudar a minimizar los cambios importantes, Angular presenta una nueva función llamada `TestBed.inject()`, que deberas usar en su lugar.
|
||||
Para obtener información sobre la eliminación de `TestBed.get()`,
|
||||
consulta su entrada en el [Índice de bajas](guide/deprecations#index).
|
||||
|
||||
</div>
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-inject-it"></code-example>
|
||||
|
||||
Or inside the `beforeEach()` if you prefer to inject the service as part of your setup.
|
||||
O dentro del `beforeEach()` si prefieres inyectar el servicio como parte de tu configuración.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="value-service-inject-before-each"> </code-example>
|
||||
|
||||
When testing a service with a dependency, provide the mock in the `providers` array.
|
||||
Al probar un servicio con una dependencia, proporcione un mock en el array de `providers`.
|
||||
|
||||
In the following example, the mock is a spy object.
|
||||
En el siguiente ejemplo, el mock es un objeto espía.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="master-service-before-each"></code-example>
|
||||
|
||||
The test consumes that spy in the same way it did earlier.
|
||||
La prueba consume ese espía de la misma manera que lo hizo antes.
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="master-service-it">
|
||||
</code-example>
|
||||
|
||||
{@a no-before-each}
|
||||
|
||||
## Testing without _beforeEach()_
|
||||
## Pruebas sin _beforeEach()_
|
||||
|
||||
Most test suites in this guide call `beforeEach()` to set the preconditions for each `it()` test
|
||||
and rely on the `TestBed` to create classes and inject services.
|
||||
La mayoría de los conjuntos de pruebas en esta guía llaman a `beforeEach()` para establecer las condiciones previas para cada prueba `it()`
|
||||
y confían en `TestBed` para crear clases e inyectar servicios.
|
||||
|
||||
There's another school of testing that never calls `beforeEach()` and prefers to create classes explicitly rather than use the `TestBed`.
|
||||
Hay otra escuela de pruebas que nunca llama a `beforeEach()` y prefiere crear clases explícitamente en lugar de usar el `TestBed`.
|
||||
|
||||
Here's how you might rewrite one of the `MasterService` tests in that style.
|
||||
Así es como podrías reescribir una de las pruebas del `MasterService` en ese estilo.
|
||||
|
||||
Begin by putting re-usable, preparatory code in a _setup_ function instead of `beforeEach()`.
|
||||
Empieza poniendo código preparatorio reutilizable en una función _setup_ en lugar de `beforeEach()`.
|
||||
|
||||
<code-example
|
||||
path="testing/src/app/demo/demo.spec.ts"
|
||||
region="no-before-each-setup"
|
||||
header="app/demo/demo.spec.ts (setup)"></code-example>
|
||||
|
||||
The `setup()` function returns an object literal
|
||||
with the variables, such as `masterService`, that a test might reference.
|
||||
You don't define _semi-global_ variables (e.g., `let masterService: MasterService`)
|
||||
in the body of the `describe()`.
|
||||
La función `setup()` devuelve un objeto literal
|
||||
con las variables, como `masterService`, a las que una prueba podría hacer referencia.
|
||||
No defines variables _semi-globales_ (por ejemplo, `let masterService: MasterService`)
|
||||
en el cuerpo de `describe()`.
|
||||
|
||||
Then each test invokes `setup()` in its first line, before continuing
|
||||
with steps that manipulate the test subject and assert expectations.
|
||||
Luego, cada prueba invoca `setup()` en su primera línea, antes de continuar
|
||||
con pasos que manipulan al sujeto de prueba y afirman expectativas.
|
||||
|
||||
<code-example
|
||||
path="testing/src/app/demo/demo.spec.ts"
|
||||
region="no-before-each-test"></code-example>
|
||||
|
||||
Notice how the test uses
|
||||
[_destructuring assignment_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
|
||||
to extract the setup variables that it needs.
|
||||
Observe cómo la prueba usa
|
||||
[_desestructuración de asignación_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
|
||||
para extraer las variables de configuración que necesita.
|
||||
|
||||
<code-example
|
||||
path="testing/src/app/demo/demo.spec.ts"
|
||||
region="no-before-each-setup-call">
|
||||
</code-example>
|
||||
|
||||
Many developers feel this approach is cleaner and more explicit than the
|
||||
traditional `beforeEach()` style.
|
||||
Muchos desarrolladores sienten que este enfoque es más limpio y explícito que el
|
||||
que el estilo tradicional `beforeEach()`.
|
||||
|
||||
Although this testing guide follows the traditional style and
|
||||
the default [CLI schematics](https://github.com/angular/angular-cli)
|
||||
generate test files with `beforeEach()` and `TestBed`,
|
||||
feel free to adopt _this alternative approach_ in your own projects.
|
||||
Aunque esta guía de prueba sigue el estilo tradicional y
|
||||
los [esquemas CLI](https://github.com/angular/angular-cli) predeterminados
|
||||
generan archivos de prueba con `beforeEach()` y `TestBed`,
|
||||
no dudes en adoptar _este enfoque alternativo_ en tus propios proyectos.
|
||||
|
||||
## Testing HTTP services
|
||||
## Pruebas de servicios HTTP
|
||||
|
||||
Data services that make HTTP calls to remote servers typically inject and delegate
|
||||
to the Angular [`HttpClient`](guide/http) service for XHR calls.
|
||||
Los servicios de datos que realizan llamadas HTTP a servidores remotos normalmente inyectan y delegan
|
||||
al servicio Angular [`HttpClient`](guide/http) para llamadas XHR.
|
||||
|
||||
You can test a data service with an injected `HttpClient` spy as you would
|
||||
test any service with a dependency.
|
||||
Puedes probar un servicio de datos con un espía `HttpClient` inyectado como lo harías
|
||||
con cualquier servicio con una dependencia.
|
||||
<code-example
|
||||
path="testing/src/app/model/hero.service.spec.ts"
|
||||
region="test-with-spies"
|
||||
@ -175,25 +175,24 @@ test any service with a dependency.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
The `HeroService` methods return `Observables`. You must
|
||||
_subscribe_ to an observable to (a) cause it to execute and (b)
|
||||
assert that the method succeeds or fails.
|
||||
Los métodos del `HeroService` devuelven `Observables`. Debes
|
||||
_subscribirte_ a un observable para (a) hacer que se ejecute y (b)
|
||||
afirmar que el método funciona o no.
|
||||
|
||||
The `subscribe()` method takes a success (`next`) and fail (`error`) callback.
|
||||
Make sure you provide _both_ callbacks so that you capture errors.
|
||||
Neglecting to do so produces an asynchronous uncaught observable error that
|
||||
the test runner will likely attribute to a completely different test.
|
||||
El método `subscribe()` toma una callback de éxito (`next`) y una de falla (`error`).
|
||||
Asegurate de proporcionar _ambas_ callback para capturar errores.
|
||||
Si no lo haces, se produce un error observable asincrónico no detectado que el
|
||||
test runner probablemente atribuirá a una prueba completamente diferente.
|
||||
|
||||
</div>
|
||||
|
||||
## _HttpClientTestingModule_
|
||||
|
||||
Extended interactions between a data service and the `HttpClient` can be complex
|
||||
and difficult to mock with spies.
|
||||
Las interacciones extendidas entre un servicio de datos y el `HttpClient` pueden ser complejas
|
||||
y difícil de crear un mock con los espías.
|
||||
|
||||
The `HttpClientTestingModule` can make these testing scenarios more manageable.
|
||||
|
||||
While the _code sample_ accompanying this guide demonstrates `HttpClientTestingModule`,
|
||||
this page defers to the [Http guide](guide/http#testing-http-requests),
|
||||
which covers testing with the `HttpClientTestingModule` in detail.
|
||||
El `HttpClientTestingModule` puede hacer que estos escenarios de prueba sean más manejables.
|
||||
|
||||
Si bien el _ejemplo de código_ que acompaña a esta guía muestra `HttpClientTestingModule`,
|
||||
esta página se remite a la [guía Http](guide/http#testing-http-requests),
|
||||
que cubre las pruebas con el `HttpClientTestingModule` en detalle.
|
||||
|
794
aio/content/guide/testing-utility-apis.en.md
Normal file
794
aio/content/guide/testing-utility-apis.en.md
Normal file
@ -0,0 +1,794 @@
|
||||
# Testing Utility APIs
|
||||
|
||||
This page describes the most useful Angular testing features.
|
||||
|
||||
The Angular testing utilities include the `TestBed`, the `ComponentFixture`, and a handful of functions that control the test environment.
|
||||
The [_TestBed_](#testbed-api-summary) and [_ComponentFixture_](#component-fixture-api-summary) classes are covered separately.
|
||||
|
||||
Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Function
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>async</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Runs the body of a test (`it`) or setup (`beforeEach`) function within a special _async test zone_.
|
||||
See [discussion above](guide/testing-components-scenarios#waitForAsync).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>fakeAsync</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Runs the body of a test (`it`) within a special _fakeAsync test zone_, enabling
|
||||
a linear control flow coding style. See [discussion above](guide/testing-components-scenarios#fake-async).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>tick</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Simulates the passage of time and the completion of pending asynchronous activities
|
||||
by flushing both _timer_ and _micro-task_ queues within the _fakeAsync test zone_.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The curious, dedicated reader might enjoy this lengthy blog post,
|
||||
["_Tasks, microtasks, queues and schedules_"](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/).
|
||||
|
||||
</div>
|
||||
|
||||
Accepts an optional argument that moves the virtual clock forward
|
||||
by the specified number of milliseconds,
|
||||
clearing asynchronous activities scheduled within that timeframe.
|
||||
See [discussion above](guide/testing-components-scenarios#tick).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>inject</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Injects one or more services from the current `TestBed` injector into a test function.
|
||||
It cannot inject a service provided by the component itself.
|
||||
See discussion of the [debugElement.injector](guide/testing-components-scenarios#get-injected-services).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>discardPeriodicTasks</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
When a `fakeAsync()` test ends with pending timer event _tasks_ (queued `setTimeOut` and `setInterval` callbacks),
|
||||
the test fails with a clear error message.
|
||||
|
||||
In general, a test should end with no queued tasks.
|
||||
When pending timer tasks are expected, call `discardPeriodicTasks` to flush the _task_ queue
|
||||
and avoid the error.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>flushMicrotasks</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
When a `fakeAsync()` test ends with pending _micro-tasks_ such as unresolved promises,
|
||||
the test fails with a clear error message.
|
||||
|
||||
In general, a test should wait for micro-tasks to finish.
|
||||
When pending microtasks are expected, call `flushMicrotasks` to flush the _micro-task_ queue
|
||||
and avoid the error.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>ComponentFixtureAutoDetect</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
A provider token for a service that turns on [automatic change detection](guide/testing-components-scenarios#automatic-change-detection).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>getTestBed</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Gets the current instance of the `TestBed`.
|
||||
Usually unnecessary because the static class methods of the `TestBed` class are typically sufficient.
|
||||
The `TestBed` instance exposes a few rarely used members that are not available as
|
||||
static methods.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
{@a testbed-class-summary}
|
||||
|
||||
## _TestBed_ class summary
|
||||
|
||||
The `TestBed` class is one of the principal Angular testing utilities.
|
||||
Its API is quite large and can be overwhelming until you've explored it,
|
||||
a little at a time. Read the early part of this guide first
|
||||
to get the basics before trying to absorb the full API.
|
||||
|
||||
The module definition passed to `configureTestingModule`
|
||||
is a subset of the `@NgModule` metadata properties.
|
||||
|
||||
<code-example language="javascript">
|
||||
type TestModuleMetadata = {
|
||||
providers?: any[];
|
||||
declarations?: any[];
|
||||
imports?: any[];
|
||||
schemas?: Array<SchemaMetadata | any[]>;
|
||||
};
|
||||
</code-example>
|
||||
|
||||
{@a metadata-override-object}
|
||||
|
||||
Each override method takes a `MetadataOverride<T>` where `T` is the kind of metadata
|
||||
appropriate to the method, that is, the parameter of an `@NgModule`,
|
||||
`@Component`, `@Directive`, or `@Pipe`.
|
||||
|
||||
<code-example language="javascript">
|
||||
type MetadataOverride<T> = {
|
||||
add?: Partial<T>;
|
||||
remove?: Partial<T>;
|
||||
set?: Partial<T>;
|
||||
};
|
||||
</code-example>
|
||||
|
||||
{@a testbed-methods}
|
||||
{@a testbed-api-summary}
|
||||
|
||||
The `TestBed` API consists of static class methods that either update or reference a _global_ instance of the `TestBed`.
|
||||
|
||||
Internally, all static methods cover methods of the current runtime `TestBed` instance,
|
||||
which is also returned by the `getTestBed()` function.
|
||||
|
||||
Call `TestBed` methods _within_ a `beforeEach()` to ensure a fresh start before each individual test.
|
||||
|
||||
Here are the most important static methods, in order of likely utility.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Methods
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>configureTestingModule</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The testing shims (`karma-test-shim`, `browser-test-shim`)
|
||||
establish the [initial test environment](guide/testing) and a default testing module.
|
||||
The default testing module is configured with basic declaratives and some Angular service substitutes that every tester needs.
|
||||
|
||||
Call `configureTestingModule` to refine the testing module configuration for a particular set of tests
|
||||
by adding and removing imports, declarations (of components, directives, and pipes), and providers.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>compileComponents</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Compile the testing module asynchronously after you've finished configuring it.
|
||||
You **must** call this method if _any_ of the testing module components have a `templateUrl`
|
||||
or `styleUrls` because fetching component template and style files is necessarily asynchronous.
|
||||
See [above](guide/testing-components-scenarios#compile-components).
|
||||
|
||||
After calling `compileComponents`, the `TestBed` configuration is frozen for the duration of the current spec.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>createComponent<T></code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Create an instance of a component of type `T` based on the current `TestBed` configuration.
|
||||
After calling `compileComponent`, the `TestBed` configuration is frozen for the duration of the current spec.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>overrideModule</code>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Replace metadata for the given `NgModule`. Recall that modules can import other modules.
|
||||
The `overrideModule` method can reach deeply into the current testing module to
|
||||
modify one of these inner modules.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>overrideComponent</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Replace metadata for the given component class, which could be nested deeply
|
||||
within an inner module.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>overrideDirective</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Replace metadata for the given directive class, which could be nested deeply
|
||||
within an inner module.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>overridePipe</code>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Replace metadata for the given pipe class, which could be nested deeply
|
||||
within an inner module.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
{@a testbed-inject}
|
||||
<code>inject</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Retrieve a service from the current `TestBed` injector.
|
||||
|
||||
The `inject` function is often adequate for this purpose.
|
||||
But `inject` throws an error if it can't provide the service.
|
||||
|
||||
What if the service is optional?
|
||||
|
||||
The `TestBed.inject()` method takes an optional second parameter,
|
||||
the object to return if Angular can't find the provider
|
||||
(`null` in this example):
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="testbed-get-w-null" header="app/demo/demo.testbed.spec.ts"></code-example>
|
||||
|
||||
After calling `TestBed.inject`, the `TestBed` configuration is frozen for the duration of the current spec.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
{@a testbed-initTestEnvironment}
|
||||
<code>initTestEnvironment</code>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Initialize the testing environment for the entire test run.
|
||||
|
||||
The testing shims (`karma-test-shim`, `browser-test-shim`) call it for you
|
||||
so there is rarely a reason for you to call it yourself.
|
||||
|
||||
You may call this method _exactly once_. If you must change
|
||||
this default in the middle of your test run, call `resetTestEnvironment` first.
|
||||
|
||||
Specify the Angular compiler factory, a `PlatformRef`, and a default Angular testing module.
|
||||
Alternatives for non-browser platforms are available in the general form
|
||||
`@angular/platform-<platform_name>/testing/<platform_name>`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>resetTestEnvironment</code>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Reset the initial test environment, including the default testing module.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
A few of the `TestBed` instance methods are not covered by static `TestBed` _class_ methods.
|
||||
These are rarely needed.
|
||||
|
||||
{@a component-fixture-api-summary}
|
||||
|
||||
## The _ComponentFixture_
|
||||
|
||||
The `TestBed.createComponent<T>`
|
||||
creates an instance of the component `T`
|
||||
and returns a strongly typed `ComponentFixture` for that component.
|
||||
|
||||
The `ComponentFixture` properties and methods provide access to the component,
|
||||
its DOM representation, and aspects of its Angular environment.
|
||||
|
||||
{@a component-fixture-properties}
|
||||
|
||||
### _ComponentFixture_ properties
|
||||
|
||||
Here are the most important properties for testers, in order of likely utility.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Properties
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>componentInstance</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The instance of the component class created by `TestBed.createComponent`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>debugElement</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The `DebugElement` associated with the root element of the component.
|
||||
|
||||
The `debugElement` provides insight into the component and its DOM element during test and debugging.
|
||||
It's a critical property for testers. The most interesting members are covered [below](#debug-element-details).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>nativeElement</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The native DOM element at the root of the component.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>changeDetectorRef</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The `ChangeDetectorRef` for the component.
|
||||
|
||||
The `ChangeDetectorRef` is most valuable when testing a
|
||||
component that has the `ChangeDetectionStrategy.OnPush` method
|
||||
or the component's change detection is under your programmatic control.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
{@a component-fixture-methods}
|
||||
|
||||
### _ComponentFixture_ methods
|
||||
|
||||
The _fixture_ methods cause Angular to perform certain tasks on the component tree.
|
||||
Call these method to trigger Angular behavior in response to simulated user action.
|
||||
|
||||
Here are the most useful methods for testers.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Methods
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>detectChanges</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Trigger a change detection cycle for the component.
|
||||
|
||||
Call it to initialize the component (it calls `ngOnInit`) and after your
|
||||
test code, change the component's data bound property values.
|
||||
Angular can't see that you've changed `personComponent.name` and won't update the `name`
|
||||
binding until you call `detectChanges`.
|
||||
|
||||
Runs `checkNoChanges` afterwards to confirm that there are no circular updates unless
|
||||
called as `detectChanges(false)`;
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>autoDetectChanges</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Set this to `true` when you want the fixture to detect changes automatically.
|
||||
|
||||
When autodetect is `true`, the test fixture calls `detectChanges` immediately
|
||||
after creating the component. Then it listens for pertinent zone events
|
||||
and calls `detectChanges` accordingly.
|
||||
When your test code modifies component property values directly,
|
||||
you probably still have to call `fixture.detectChanges` to trigger data binding updates.
|
||||
|
||||
The default is `false`. Testers who prefer fine control over test behavior
|
||||
tend to keep it `false`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>checkNoChanges</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Do a change detection run to make sure there are no pending changes.
|
||||
Throws an exceptions if there are.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>isStable</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
If the fixture is currently _stable_, returns `true`.
|
||||
If there are async tasks that have not completed, returns `false`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>whenStable</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Returns a promise that resolves when the fixture is stable.
|
||||
|
||||
To resume testing after completion of asynchronous activity or
|
||||
asynchronous change detection, hook that promise.
|
||||
See [above](guide/testing-components-scenarios#when-stable).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>destroy</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Trigger component destruction.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
{@a debug-element-details}
|
||||
|
||||
#### _DebugElement_
|
||||
|
||||
The `DebugElement` provides crucial insights into the component's DOM representation.
|
||||
|
||||
From the test root component's `DebugElement` returned by `fixture.debugElement`,
|
||||
you can walk (and query) the fixture's entire element and component subtrees.
|
||||
|
||||
Here are the most useful `DebugElement` members for testers, in approximate order of utility:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Member
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>nativeElement</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The corresponding DOM element in the browser (null for WebWorkers).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>query</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Calling `query(predicate: Predicate<DebugElement>)` returns the first `DebugElement`
|
||||
that matches the [predicate](#query-predicate) at any depth in the subtree.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>queryAll</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Calling `queryAll(predicate: Predicate<DebugElement>)` returns all `DebugElements`
|
||||
that matches the [predicate](#query-predicate) at any depth in subtree.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>injector</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The host dependency injector.
|
||||
For example, the root element's component instance injector.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>componentInstance</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The element's own component instance, if it has one.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>context</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
An object that provides parent context for this element.
|
||||
Often an ancestor component instance that governs this element.
|
||||
|
||||
When an element is repeated within `*ngFor`, the context is an `NgForRow` whose `$implicit`
|
||||
property is the value of the row instance value.
|
||||
For example, the `hero` in `*ngFor="let hero of heroes"`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>children</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The immediate `DebugElement` children. Walk the tree by descending through `children`.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
`DebugElement` also has `childNodes`, a list of `DebugNode` objects.
|
||||
`DebugElement` derives from `DebugNode` objects and there are often
|
||||
more nodes than elements. Testers can usually ignore plain nodes.
|
||||
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>parent</code>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
The `DebugElement` parent. Null if this is the root element.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>name</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The element tag name, if it is an element.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>triggerEventHandler</code>
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Triggers the event by its name if there is a corresponding listener
|
||||
in the element's `listeners` collection.
|
||||
The second parameter is the _event object_ expected by the handler.
|
||||
See [above](guide/testing-components-scenarios#trigger-event-handler).
|
||||
|
||||
If the event lacks a listener or there's some other problem,
|
||||
consider calling `nativeElement.dispatchEvent(eventObject)`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>listeners</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The callbacks attached to the component's `@Output` properties and/or the element's event properties.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>providerTokens</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
This component's injector lookup tokens.
|
||||
Includes the component itself plus the tokens that the component lists in its `providers` metadata.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>source</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Where to find this element in the source component template.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>references</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Dictionary of objects associated with template local variables (e.g. `#foo`),
|
||||
keyed by the local variable name.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
{@a query-predicate}
|
||||
|
||||
The `DebugElement.query(predicate)` and `DebugElement.queryAll(predicate)` methods take a
|
||||
predicate that filters the source element's subtree for matching `DebugElement`.
|
||||
|
||||
The predicate is any method that takes a `DebugElement` and returns a _truthy_ value.
|
||||
The following example finds all `DebugElements` with a reference to a template local variable named "content":
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="custom-predicate" header="app/demo/demo.testbed.spec.ts"></code-example>
|
||||
|
||||
The Angular `By` class has three static methods for common predicates:
|
||||
|
||||
- `By.all` - return all elements.
|
||||
- `By.css(selector)` - return elements with matching CSS selectors.
|
||||
- `By.directive(directive)` - return elements that Angular matched to an instance of the directive class.
|
||||
|
||||
<code-example path="testing/src/app/hero/hero-list.component.spec.ts" region="by" header="app/hero/hero-list.component.spec.ts"></code-example>
|
||||
|
||||
<hr>
|
||||
|
@ -1,32 +1,34 @@
|
||||
# Testing Utility APIs
|
||||
# APIs de Utilidades de Testing
|
||||
|
||||
This page describes the most useful Angular testing features.
|
||||
Esta página describe las funciones de testing más útiles de Angular
|
||||
|
||||
The Angular testing utilities include the `TestBed`, the `ComponentFixture`, and a handful of functions that control the test environment.
|
||||
The [_TestBed_](#testbed-api-summary) and [_ComponentFixture_](#component-fixture-api-summary) classes are covered separately.
|
||||
Las funciones de testing de Angular incluyen la `TestBed` , el `ComponentFixture` y varias funciones que controlan el medio de pruebas
|
||||
|
||||
Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
Las clases [_TestBed_](#testbed-api-summary) y [_ComponentFixture_](#component-fixture-api-summary) se tratan aparte.
|
||||
|
||||
Este es un resumen de todas las funciones autocontenidas, en orden de posible utilidad:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Function
|
||||
Función
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
Descripción
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>async</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Runs the body of a test (`it`) or setup (`beforeEach`) function within a special _async test zone_.
|
||||
See [discussion above](guide/testing-components-scenarios#waitForAsync).
|
||||
|
||||
|
||||
Ejecuta el conjunto de una función test (`it`) o setup (`beforeEach`) desde una _zona de pruebas asíncrona_
|
||||
Consulta [esta discusión](guide/testing-components-scenarios#waitForAsync).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -36,10 +38,10 @@ Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Runs the body of a test (`it`) within a special _fakeAsync test zone_, enabling
|
||||
a linear control flow coding style. See [discussion above](guide/testing-components-scenarios#fake-async).
|
||||
|
||||
|
||||
Ejecuta el conjunto de un test (`it`) desde una _zona falsa de pruebas asíncrona_ especial, permitiendo un estilo de código de flujo de control lineal.
|
||||
Consulta [esta discusión](guide/testing-components-scenarios#fake-async).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -49,22 +51,19 @@ Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Simulates the passage of time and the completion of pending asynchronous activities
|
||||
by flushing both _timer_ and _micro-task_ queues within the _fakeAsync test zone_.
|
||||
|
||||
|
||||
Simula el paso del tiempo y completar actividades asíncronas pendientes haciendo flush tanto en el _cronómetro_ como en la _cola de micro-tareas_ desde la _zona falsa de pruebas asíncronas_
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The curious, dedicated reader might enjoy this lengthy blog post,
|
||||
Algún lector curioso y dedicado quizá disfrute de la lectura de esta extensa publicación en un blog:
|
||||
["_Tasks, microtasks, queues and schedules_"](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/).
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
Accepts an optional argument that moves the virtual clock forward
|
||||
by the specified number of milliseconds,
|
||||
clearing asynchronous activities scheduled within that timeframe.
|
||||
See [discussion above](guide/testing-components-scenarios#tick).
|
||||
|
||||
|
||||
Acepta un argumento adicionar que adelanta el reloj virtual según el número especificado de milisegundos, despejando las actividades asíncronas planeadas para ese bloque de tiempo
|
||||
|
||||
Consulta [esta discusión](guide/testing-components-scenarios#tick).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -74,11 +73,11 @@ Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Injects one or more services from the current `TestBed` injector into a test function.
|
||||
It cannot inject a service provided by the component itself.
|
||||
See discussion of the [debugElement.injector](guide/testing-components-scenarios#get-injected-services).
|
||||
|
||||
|
||||
Inyecta uno o más servicios desde la `TestBed` inyectora actual hacia una función de test.
|
||||
No puede inyectar un servicio proveído por el componente en sí.
|
||||
Consulta [debugElement.injector](guide/testing-components-scenarios#get-injected-services).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -88,14 +87,11 @@ Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
When a `fakeAsync()` test ends with pending timer event _tasks_ (queued `setTimeOut` and `setInterval` callbacks),
|
||||
the test fails with a clear error message.
|
||||
|
||||
In general, a test should end with no queued tasks.
|
||||
When pending timer tasks are expected, call `discardPeriodicTasks` to flush the _task_ queue
|
||||
and avoid the error.
|
||||
|
||||
|
||||
Cuando un `fakeAsync()` test finaliza con tareas cronometradas pendientes (llamadas a `setTimeOut` y `setInterval` en cola), el test finaliza con un mensaje de error vacío.
|
||||
|
||||
En general, un test debería finalizar sin tareas en cola. Cuando esperamos tareas cronometradas pendientes, llamamos a `discardPeriodicTasks` para hacer flush a la cola de tareas y evitar el error.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -105,14 +101,10 @@ Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
When a `fakeAsync()` test ends with pending _micro-tasks_ such as unresolved promises,
|
||||
the test fails with a clear error message.
|
||||
|
||||
In general, a test should wait for micro-tasks to finish.
|
||||
When pending microtasks are expected, call `flushMicrotasks` to flush the _micro-task_ queue
|
||||
and avoid the error.
|
||||
|
||||
Cuando un test `fakeAsync()` finaliza con micro-tareas pendientes como promesas sin resolver, el test finaliza con un mensaje de error vacío
|
||||
|
||||
En general, un test debería esperar a que acaben las micro-tareas. Cuando quedan micro-tareas pendientes en cola, llamamos a `flushMicrotasks` para hacer flush a la cola de micro-tareas y evitar el error.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -122,9 +114,8 @@ Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
A provider token for a service that turns on [automatic change detection](guide/testing-components-scenarios#automatic-change-detection).
|
||||
|
||||
Un token del proveedor que inicia la [detección automática de cambios](guide/testing-components-scenarios#automatic-change-detection).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -134,29 +125,24 @@ Here's a summary of the stand-alone functions, in order of likely utility:
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Gets the current instance of the `TestBed`.
|
||||
Usually unnecessary because the static class methods of the `TestBed` class are typically sufficient.
|
||||
The `TestBed` instance exposes a few rarely used members that are not available as
|
||||
static methods.
|
||||
|
||||
|
||||
Toma la instancia actual de la `TestBed`.
|
||||
Normalmente es innecesaria porque los métodos de clase estáticos de `TestBed` suelen ser suficientes.
|
||||
La instancia de `TestBed` muestra algunos miembros menos comunes que no están disponibles como métodos estáticos
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
{@a testbed-class-summary}
|
||||
{@a resumen-clase-testbed}
|
||||
|
||||
## _TestBed_ class summary
|
||||
## Resumen de la clase _TestBed_
|
||||
|
||||
The `TestBed` class is one of the principal Angular testing utilities.
|
||||
Its API is quite large and can be overwhelming until you've explored it,
|
||||
a little at a time. Read the early part of this guide first
|
||||
to get the basics before trying to absorb the full API.
|
||||
La clase `TestBed` es una de las utilidades de testing principales de Angular. Su API es bastante grande y puede ser sobrecogedora hasta que la has explorado, ve poco a poco. Puedes leer la parte inicial de esta guía primero para familiarizarte con lo básico antes de intentar aprender toda la API.
|
||||
|
||||
The module definition passed to `configureTestingModule`
|
||||
is a subset of the `@NgModule` metadata properties.
|
||||
La definición del módulo que pasamos a `configureTestingModule` es un subconjunto de las propiedades metadata de `@NgModule`.
|
||||
|
||||
<code-example language="javascript">
|
||||
type TestModuleMetadata = {
|
||||
@ -169,9 +155,8 @@ is a subset of the `@NgModule` metadata properties.
|
||||
|
||||
{@a metadata-override-object}
|
||||
|
||||
Each override method takes a `MetadataOverride<T>` where `T` is the kind of metadata
|
||||
appropriate to the method, that is, the parameter of an `@NgModule`,
|
||||
`@Component`, `@Directive`, or `@Pipe`.
|
||||
Cada método de sobreescribir toma un `MetadataOverride<T>` donde `T` es el tipo de metadato apropiado para el método, es decir, el parámetro de un `@NgModule`,
|
||||
`@Component`, `@Directive`, o `@Pipe`.
|
||||
|
||||
<code-example language="javascript">
|
||||
type MetadataOverride<T> = {
|
||||
@ -181,42 +166,40 @@ appropriate to the method, that is, the parameter of an `@NgModule`,
|
||||
};
|
||||
</code-example>
|
||||
|
||||
{@a testbed-methods}
|
||||
{@a testbed-métodos}
|
||||
{@a testbed-api-summary}
|
||||
|
||||
The `TestBed` API consists of static class methods that either update or reference a _global_ instance of the `TestBed`.
|
||||
La API `TestBed` consiste de métodos de clase estáticos que o actualizan o referencian una instancia global de `TestBed`.
|
||||
|
||||
Internally, all static methods cover methods of the current runtime `TestBed` instance,
|
||||
which is also returned by the `getTestBed()` function.
|
||||
Internamente, todos los métodos estáticos cubren los métodos de la instancia `TestBed` actual, lo cual también es devuelto por la función `getTestBed()`.
|
||||
|
||||
Call `TestBed` methods _within_ a `beforeEach()` to ensure a fresh start before each individual test.
|
||||
Llama a los métodos `TestBed` *desde* un `beforeEach()` para asegurarte de tener un inicio en blanco antes de cada test individual.
|
||||
|
||||
Here are the most important static methods, in order of likely utility.
|
||||
Aquí están los métodos estáticos más importantes, en orden de posible utilidad.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Methods
|
||||
Métodos
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
Descripción
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>configureTestingModule</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The testing shims (`karma-test-shim`, `browser-test-shim`)
|
||||
establish the [initial test environment](guide/testing) and a default testing module.
|
||||
The default testing module is configured with basic declaratives and some Angular service substitutes that every tester needs.
|
||||
|
||||
Call `configureTestingModule` to refine the testing module configuration for a particular set of tests
|
||||
by adding and removing imports, declarations (of components, directives, and pipes), and providers.
|
||||
|
||||
|
||||
Los shims de prueba (`karma-test-shim, `browser-test-shim`) establecen el [medio de pruebas inicial](guide/testing)y un módulo de pruebas por defecto.
|
||||
El módulo de pruebas por defecto es configurado con declarativas básicas y algunos servicios sustitutos de Angular que cualquier tester necesitaría.
|
||||
|
||||
Llama a `configureTestingModule` para refinar la configuración del módulo de pruebas para un conjunto particular de tests, añadiendo o quitando importes, declaraciones (de componentes, directivas, pipes...) y proveedores.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -226,14 +209,14 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Compile the testing module asynchronously after you've finished configuring it.
|
||||
You **must** call this method if _any_ of the testing module components have a `templateUrl`
|
||||
or `styleUrls` because fetching component template and style files is necessarily asynchronous.
|
||||
See [above](guide/testing-components-scenarios#compile-components).
|
||||
|
||||
After calling `compileComponents`, the `TestBed` configuration is frozen for the duration of the current spec.
|
||||
|
||||
|
||||
Compila el módulo de testing de forma asíncrona después de que hayas finalizado configurándolo.
|
||||
Debes llamar este método si cualquiera de los componentes de módulo de testing tiene una `templateUrl` o `styleUrls`, porque traer templates de componentes y archivos de estilo es obligatoriamente asíncrono.
|
||||
|
||||
Consulta [aquí](guide/testing-components-scenarios#compile-components).
|
||||
|
||||
Después de llamar a `compileComponents`, la configuración de `TestBed` se congela durante la especificación actual.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -243,10 +226,10 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Create an instance of a component of type `T` based on the current `TestBed` configuration.
|
||||
After calling `compileComponent`, the `TestBed` configuration is frozen for the duration of the current spec.
|
||||
|
||||
|
||||
Crea una instancia de un componente de tipo `T` basado en la configuración de la `TestBed` actual.
|
||||
Despuest de llamar a `compileComponent`, la configuración de `TestBed` se congela durante la especificación actual.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -256,10 +239,9 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Replace metadata for the given `NgModule`. Recall that modules can import other modules.
|
||||
The `overrideModule` method can reach deeply into the current testing module to
|
||||
modify one of these inner modules.
|
||||
|
||||
Reemplaza metadatos del `NgModule` proporcionado. Recuerde que los módulos pueden importar otros módulos.
|
||||
El método `overrideModule` puede ir hasta el fondo del módulo testing actual para modificar alguno de estos módulos internos
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -269,10 +251,9 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Replace metadata for the given component class, which could be nested deeply
|
||||
within an inner module.
|
||||
|
||||
|
||||
Reemplaza metadatos para la clase componente dada, la cual puede estar anidada dentro de un módulo interno.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -282,10 +263,9 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Replace metadata for the given directive class, which could be nested deeply
|
||||
within an inner module.
|
||||
|
||||
|
||||
Reemplaza metadatos para la clase directiva dada, la cual puede estar anidada dentro de un módulo interno.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -295,9 +275,8 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Replace metadata for the given pipe class, which could be nested deeply
|
||||
within an inner module.
|
||||
|
||||
Reemplaza metadatos para la clase pipe dada, la cual puede estar anidada dentro de un módulo interno.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -308,22 +287,19 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Retrieve a service from the current `TestBed` injector.
|
||||
|
||||
The `inject` function is often adequate for this purpose.
|
||||
But `inject` throws an error if it can't provide the service.
|
||||
|
||||
What if the service is optional?
|
||||
|
||||
The `TestBed.inject()` method takes an optional second parameter,
|
||||
the object to return if Angular can't find the provider
|
||||
(`null` in this example):
|
||||
|
||||
|
||||
Trae un servicio del inyector `TestBed` actual.
|
||||
|
||||
La función `inject` normalmente es adecuada para esto, pero lanza un error si no puede proveer el servicio
|
||||
|
||||
¿Qué pasa si el servicio es opcional?
|
||||
|
||||
El método `TestBed.inject()` toma un segundo parámetro opcional, el objeto para devolver si Angular no encuentra el proveedor (nulo, en este ejemplo):
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="testbed-get-w-null" header="app/demo/demo.testbed.spec.ts"></code-example>
|
||||
|
||||
After calling `TestBed.inject`, the `TestBed` configuration is frozen for the duration of the current spec.
|
||||
|
||||
|
||||
Después de llamar a `TestBed.inject`, la configuración de `TestBed` se congela durante la especificación actual.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -334,18 +310,16 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Initialize the testing environment for the entire test run.
|
||||
|
||||
The testing shims (`karma-test-shim`, `browser-test-shim`) call it for you
|
||||
so there is rarely a reason for you to call it yourself.
|
||||
|
||||
You may call this method _exactly once_. If you must change
|
||||
this default in the middle of your test run, call `resetTestEnvironment` first.
|
||||
|
||||
Specify the Angular compiler factory, a `PlatformRef`, and a default Angular testing module.
|
||||
Alternatives for non-browser platforms are available in the general form
|
||||
Inicializa el medio de testing para todo el test run.
|
||||
|
||||
Los shims de pruebas (`karma-test-shim`, `browser-test-shim`) lo llaman por ti, así que no suele haber un motivo para usarlo.
|
||||
|
||||
Puedes llamar este método _exactamente una vez_. Si debes cambiar este valor por defecto en mitad de un test run, utiliza `resetTestEnvironment` primero.
|
||||
|
||||
Especifica el compilador de fábrica Angular, un `PlatformRef` y un módulo por defecto de pruebas de Angular.
|
||||
Existen alternativas para plataformas no basadas en navegador en el formulario general siguiente:
|
||||
`@angular/platform-<platform_name>/testing/<platform_name>`.
|
||||
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -355,39 +329,35 @@ Here are the most important static methods, in order of likely utility.
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Reset the initial test environment, including the default testing module.
|
||||
|
||||
Resetea el medio de pruebas inicial, incluyendo el módulo de pruebas por defecto.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
A few of the `TestBed` instance methods are not covered by static `TestBed` _class_ methods.
|
||||
These are rarely needed.
|
||||
Algunos de los métodos de instancia de `TestBed` no son cubiertos por los métodos estáticos de clase de `TestBed`. Estos no suelen utilizarse.
|
||||
|
||||
{@a component-fixture-api-summary}
|
||||
|
||||
## The _ComponentFixture_
|
||||
## El _ComponentFixture_
|
||||
|
||||
The `TestBed.createComponent<T>`
|
||||
creates an instance of the component `T`
|
||||
and returns a strongly typed `ComponentFixture` for that component.
|
||||
`TestBed.createComponent<T>` crea una instancia de un componente `T` y devuelve un `ComponentFixture` fuertemente tipificado para ese componente
|
||||
|
||||
The `ComponentFixture` properties and methods provide access to the component,
|
||||
its DOM representation, and aspects of its Angular environment.
|
||||
Las propiedades y métodos de `ComponentFixture` permiten acceso al componente, su representación DOM y algunos aspectos del medio Angular.
|
||||
|
||||
{@a component-fixture-properties}
|
||||
{@a componentes-fixture-propiedades}
|
||||
|
||||
### _ComponentFixture_ properties
|
||||
### Propiedades de _ComponentFixture_
|
||||
|
||||
Here are the most important properties for testers, in order of likely utility.
|
||||
Aquí están las propiedades más importantes para testers, en orden de posible utilidad.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Properties
|
||||
Propiedades
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
Descripción
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
@ -397,9 +367,9 @@ Here are the most important properties for testers, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The instance of the component class created by `TestBed.createComponent`.
|
||||
|
||||
|
||||
La instancia de la clase componente creada por `TestBed.createComponent`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -409,12 +379,13 @@ Here are the most important properties for testers, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The `DebugElement` associated with the root element of the component.
|
||||
|
||||
The `debugElement` provides insight into the component and its DOM element during test and debugging.
|
||||
It's a critical property for testers. The most interesting members are covered [below](#debug-element-details).
|
||||
|
||||
|
||||
El `DebugElement` asociado con el elemento raíz del componente.
|
||||
|
||||
El `DebugElement` da información sobre el componente y su elemento DOM durante el test y debug.
|
||||
|
||||
Es una propiedad crítica para los testers. Los miembros más interesantes están cubiertos [aquí](#debug-element-details).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -424,9 +395,9 @@ Here are the most important properties for testers, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The native DOM element at the root of the component.
|
||||
|
||||
|
||||
El elemento DOM nativo en la raíz del componente.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -436,53 +407,48 @@ Here are the most important properties for testers, in order of likely utility.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The `ChangeDetectorRef` for the component.
|
||||
|
||||
The `ChangeDetectorRef` is most valuable when testing a
|
||||
component that has the `ChangeDetectionStrategy.OnPush` method
|
||||
or the component's change detection is under your programmatic control.
|
||||
|
||||
|
||||
El `ChangeDetectorRef` para el componente.
|
||||
|
||||
El `ChangeDetectorRef` es más valioso cuando testeamos un componente que tiene el método`ChangeDetectionStrategy.OnPush` o cuando la detección de cambios del componente está bajo tu control programático.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
{@a component-fixture-methods}
|
||||
{@a componente-fixture-métodos}
|
||||
|
||||
### _ComponentFixture_ methods
|
||||
### Métodos de _ComponentFixture_
|
||||
|
||||
The _fixture_ methods cause Angular to perform certain tasks on the component tree.
|
||||
Call these method to trigger Angular behavior in response to simulated user action.
|
||||
Los métodos fixture hacen que Angular ejecute mejor ciertas tareas en el árbol de componentes. Llama a estos métodos para iniciar el comportamiento de Angular en respuesta a una acción de usuario simulada.
|
||||
|
||||
Here are the most useful methods for testers.
|
||||
Aquí están los métodos más útiles para los testers.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Methods
|
||||
Métodos
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
Descripción
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td style="vertical-align: top">
|
||||
<code>detectChanges</code>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Trigger a change detection cycle for the component.
|
||||
|
||||
Call it to initialize the component (it calls `ngOnInit`) and after your
|
||||
test code, change the component's data bound property values.
|
||||
Angular can't see that you've changed `personComponent.name` and won't update the `name`
|
||||
binding until you call `detectChanges`.
|
||||
|
||||
Runs `checkNoChanges` afterwards to confirm that there are no circular updates unless
|
||||
called as `detectChanges(false)`;
|
||||
|
||||
|
||||
Inicia un ciclo de detección de cambios para el componente.
|
||||
|
||||
Llámalo para inicializar el componente (que llama a `ngOnInit`) y después de tu código de pruebas, cambia los valores de propiedad asociados a los datos de los componentes.
|
||||
Angular no puede ver que has cambiado `personComponent.name` y no actualizará el `name` hasta que llames a `detectChanges`.
|
||||
|
||||
Ejecuta `checkNoChanges` después para confirmar que no hay actualizaciones circulares, a no se que se llame así: `detectChanges(false)`
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -492,18 +458,15 @@ Here are the most useful methods for testers.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
|
||||
Poner esto a `true` cuando quieras que el fixture detecte los cambios automáticamente.
|
||||
Set this to `true` when you want the fixture to detect changes automatically.
|
||||
|
||||
When autodetect is `true`, the test fixture calls `detectChanges` immediately
|
||||
after creating the component. Then it listens for pertinent zone events
|
||||
and calls `detectChanges` accordingly.
|
||||
When your test code modifies component property values directly,
|
||||
you probably still have to call `fixture.detectChanges` to trigger data binding updates.
|
||||
|
||||
The default is `false`. Testers who prefer fine control over test behavior
|
||||
tend to keep it `false`.
|
||||
|
||||
|
||||
Cuando autodetect es `true`, el fixture de pruebas llama a `detectChanges` inmediatamente después de crear el componente. Después comprueba los eventos de zona pertinentes y llama a `detectChanges` de forma acorde.
|
||||
Cuando tu código de pruebas modifique los valores de propiedad de un componente de forma directa, probablemente tengas que llamar a `fixture.detectChanges` para iniciar las actualizaciones de unificación de datos.
|
||||
|
||||
El valor por defecto es `false`. Los testers que prefieren tener un control mayor sobre el comportamiento de pruebas suelen dejarlo en `false`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -513,9 +476,10 @@ Here are the most useful methods for testers.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Do a change detection run to make sure there are no pending changes.
|
||||
Throws an exceptions if there are.
|
||||
|
||||
Corre el programa para detectar cambios y asegurarse de que no hay cambios pendientes.
|
||||
Lanza una excepción si los hay.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -525,10 +489,10 @@ Here are the most useful methods for testers.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
If the fixture is currently _stable_, returns `true`.
|
||||
If there are async tasks that have not completed, returns `false`.
|
||||
|
||||
|
||||
Si el fixture es actualmente estable, devuelve `true`.
|
||||
Si hay tareas asíncronas no completadas, devuelve `false`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -538,13 +502,13 @@ Here are the most useful methods for testers.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Returns a promise that resolves when the fixture is stable.
|
||||
|
||||
To resume testing after completion of asynchronous activity or
|
||||
asynchronous change detection, hook that promise.
|
||||
See [above](guide/testing-components-scenarios#when-stable).
|
||||
|
||||
|
||||
Devuelve una promesa que resuelve cuando el fixture es estable.
|
||||
|
||||
Para volver al testing después de completar actividad asíncrona o detección de cambios asíncronos, añade esta promesa.
|
||||
|
||||
Consulta [aquí](guide/testing-components-scenarios#when-stable).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -554,31 +518,30 @@ Here are the most useful methods for testers.
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Trigger component destruction.
|
||||
|
||||
|
||||
Inicia la destrucción del componente
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
{@a debug-element-details}
|
||||
{@a debug-elementos-detalles}
|
||||
|
||||
#### _DebugElement_
|
||||
|
||||
The `DebugElement` provides crucial insights into the component's DOM representation.
|
||||
El `DebugElement` proporciona información crucial para la representación DOM de los componentes.
|
||||
|
||||
From the test root component's `DebugElement` returned by `fixture.debugElement`,
|
||||
you can walk (and query) the fixture's entire element and component subtrees.
|
||||
Desde el `DebugElement` del componente test raíz, devuelto por `fixture.debugElement`, puedes llegar a todo elemento y subárbol de componentes del fixture
|
||||
|
||||
Here are the most useful `DebugElement` members for testers, in approximate order of utility:
|
||||
Aquí están los miembros `DebugElement` más útiles para los testers, en orden de posible utilidad:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>
|
||||
Member
|
||||
Miembro
|
||||
</th>
|
||||
<th>
|
||||
Description
|
||||
Descripción
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
@ -588,9 +551,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The corresponding DOM element in the browser (null for WebWorkers).
|
||||
|
||||
El elemento DOM correspondiente en el navegador (nulo para WebWorkers).
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -600,10 +562,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Calling `query(predicate: Predicate<DebugElement>)` returns the first `DebugElement`
|
||||
that matches the [predicate](#query-predicate) at any depth in the subtree.
|
||||
|
||||
Llamar a `query(predicate: Predicate<DebugElement>)` devuelbe el primer `DebugElement` que coincida con el [predicado](#query-predicate) a cualquier profundidad en el subárbol
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -613,10 +573,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Calling `queryAll(predicate: Predicate<DebugElement>)` returns all `DebugElements`
|
||||
that matches the [predicate](#query-predicate) at any depth in subtree.
|
||||
|
||||
Llamar a `queryAll(predicate: Predicate<DebugElement>)` devuelve todos los `DebugElements` que coincidan con el [predicado](#query-predicate) a cualquier profundidad en el subárbol
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -626,10 +584,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The host dependency injector.
|
||||
For example, the root element's component instance injector.
|
||||
|
||||
El inyector de dependecia del host. Por ejemplo, el inyector de la instancia del componente del elemento
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -639,9 +595,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The element's own component instance, if it has one.
|
||||
|
||||
La instancia del componente del propio elemento, si tiene.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -651,14 +606,12 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
An object that provides parent context for this element.
|
||||
Often an ancestor component instance that governs this element.
|
||||
|
||||
When an element is repeated within `*ngFor`, the context is an `NgForRow` whose `$implicit`
|
||||
property is the value of the row instance value.
|
||||
For example, the `hero` in `*ngFor="let hero of heroes"`.
|
||||
|
||||
|
||||
Un objeto que provee contexto del padre para este elemento.
|
||||
En muchas ocasiones una instancia del componente ancestro gobierna este elemento.
|
||||
|
||||
Cuando un elemento se repite en `*ngFor`, el contexto es un `NgForRow` cuya propiedad `$implicit` es el valor de la instancia de la fila. Por ejemplo, el `hero` en *ngFor="let hero of heroes"`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -668,15 +621,14 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The immediate `DebugElement` children. Walk the tree by descending through `children`.
|
||||
|
||||
|
||||
Los hijos `DebugElement` inmediatos. Recorre el árbol descendiendo a través de los hijos.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
`DebugElement` also has `childNodes`, a list of `DebugNode` objects.
|
||||
`DebugElement` derives from `DebugNode` objects and there are often
|
||||
more nodes than elements. Testers can usually ignore plain nodes.
|
||||
|
||||
|
||||
`DebugElement` también tiene `childNodes`, una lista de objetos `DebugNode`.
|
||||
`DebugElement` deriva de los objetos `DebugNode` y suele haber más nodos que elementos. Los tester normalmente ignoran los nodos planos.
|
||||
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@ -687,8 +639,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
<td>
|
||||
|
||||
The `DebugElement` parent. Null if this is the root element.
|
||||
|
||||
El `DebugElement` padre. Es nulo si este es el elemento raíz.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -698,9 +650,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The element tag name, if it is an element.
|
||||
|
||||
El tag name del elemento, si es que es un elemento.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -710,14 +661,13 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Triggers the event by its name if there is a corresponding listener
|
||||
in the element's `listeners` collection.
|
||||
The second parameter is the _event object_ expected by the handler.
|
||||
See [above](guide/testing-components-scenarios#trigger-event-handler).
|
||||
|
||||
If the event lacks a listener or there's some other problem,
|
||||
consider calling `nativeElement.dispatchEvent(eventObject)`.
|
||||
|
||||
Inicia el evento por su nombre si hay un receptor correspondiente en la colección `listeners` del elemento.
|
||||
El segundo parámetro es el _objeto evento_ esperado por el handler.
|
||||
|
||||
Consulta [aquí](guide/testing-components-scenarios#trigger-event-handler).
|
||||
|
||||
Si el evento no tiene un receptor o hay algún problema, considera llamar a `nativeElement.dispatchEvent(eventObject)`.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -727,9 +677,9 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
The callbacks attached to the component's `@Output` properties and/or the element's event properties.
|
||||
|
||||
|
||||
Los callbacks insertados al `@Output` del componente, sus propiedades y/o las propiedades de evento del elemento.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -739,10 +689,9 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
This component's injector lookup tokens.
|
||||
Includes the component itself plus the tokens that the component lists in its `providers` metadata.
|
||||
|
||||
Los token de búsqueda del inyector de este componente.
|
||||
Include el componente en sí mismo además de los tokens que el componente lista en la parte "proveedores" de sus metadatos.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -752,9 +701,8 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Where to find this element in the source component template.
|
||||
|
||||
Dónde encontrar este elemento en el componente template fuente.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -764,31 +712,28 @@ Here are the most useful `DebugElement` members for testers, in approximate orde
|
||||
</td>
|
||||
|
||||
<td>
|
||||
|
||||
Dictionary of objects associated with template local variables (e.g. `#foo`),
|
||||
keyed by the local variable name.
|
||||
|
||||
Diccionario de objetos asociados a variables locales template (e.g. `#foo`), acuñado por el nombre de la variable local
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
{@a query-predicate}
|
||||
|
||||
The `DebugElement.query(predicate)` and `DebugElement.queryAll(predicate)` methods take a
|
||||
predicate that filters the source element's subtree for matching `DebugElement`.
|
||||
Los métodos `DebugElement.query(predicate)` y`DebugElement.queryAll(predicate)` toman un predicado que filtra el subárbol del elemento fuente para igualar a `DebugElement`.
|
||||
|
||||
The predicate is any method that takes a `DebugElement` and returns a _truthy_ value.
|
||||
The following example finds all `DebugElements` with a reference to a template local variable named "content":
|
||||
El predicado es cualquier método que tome el `DebugElement` y devuelva un valor verdadero.
|
||||
|
||||
El siguiente ejemplo encuentra todos los `DebugElement` con una referencia a una variable local template llamada "content":
|
||||
|
||||
<code-example path="testing/src/app/demo/demo.testbed.spec.ts" region="custom-predicate" header="app/demo/demo.testbed.spec.ts"></code-example>
|
||||
|
||||
The Angular `By` class has three static methods for common predicates:
|
||||
La clase Angular `By` tiene tres métodos estáticos para predicados comunes:
|
||||
|
||||
- `By.all` - return all elements.
|
||||
- `By.css(selector)` - return elements with matching CSS selectors.
|
||||
- `By.directive(directive)` - return elements that Angular matched to an instance of the directive class.
|
||||
- `By.all` - devuelve todos los elementos
|
||||
- `By.css(selector)` - devuelve los elementos con selectores CSS coincidentes
|
||||
- `By.directive(directive)` - devuelve elementos que Angular ha unido a una instancia de la clase directiva.
|
||||
|
||||
<code-example path="testing/src/app/hero/hero-list.component.spec.ts" region="by" header="app/hero/hero-list.component.spec.ts"></code-example>
|
||||
|
||||
<hr>
|
||||
|
||||
|
76
aio/content/guide/two-way-binding.en.md
Normal file
76
aio/content/guide/two-way-binding.en.md
Normal file
@ -0,0 +1,76 @@
|
||||
# Two-way binding `[(...)]`
|
||||
|
||||
Two-way binding gives your app a way to share data between a component class and
|
||||
its template.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example></live-example> for a working example containing the code snippets in this guide.
|
||||
|
||||
</div>
|
||||
|
||||
## Basics of two-way binding
|
||||
|
||||
Two-way binding does two things:
|
||||
|
||||
1. Sets a specific element property.
|
||||
1. Listens for an element change event.
|
||||
|
||||
Angular offers a special _two-way data binding_ syntax for this purpose, `[()]`.
|
||||
The `[()]` syntax combines the brackets
|
||||
of property binding, `[]`, with the parentheses of event binding, `()`.
|
||||
|
||||
<div class="callout is-important">
|
||||
|
||||
<header>
|
||||
[( )] = banana in a box
|
||||
</header>
|
||||
|
||||
Visualize a *banana in a box* to remember that the parentheses go _inside_ the brackets.
|
||||
|
||||
</div>
|
||||
|
||||
The `[()]` syntax is easy to demonstrate when the element has a settable
|
||||
property called `x` and a corresponding event named `xChange`.
|
||||
Here's a `SizerComponent` that fits this pattern.
|
||||
It has a `size` value property and a companion `sizeChange` event:
|
||||
|
||||
<code-example path="two-way-binding/src/app/sizer/sizer.component.ts" header="src/app/sizer.component.ts"></code-example>
|
||||
|
||||
<code-example path="two-way-binding/src/app/sizer/sizer.component.html" header="src/app/sizer.component.html"></code-example>
|
||||
|
||||
The initial `size` is an input value from a property binding.
|
||||
Clicking the buttons increases or decreases the `size`, within
|
||||
min/max value constraints,
|
||||
and then raises, or emits, the `sizeChange` event with the adjusted size.
|
||||
|
||||
Here's an example in which the `AppComponent.fontSizePx` is two-way bound to the `SizerComponent`:
|
||||
|
||||
<code-example path="two-way-binding/src/app/app.component.html" header="src/app/app.component.html (two-way-1)" region="two-way-1"></code-example>
|
||||
|
||||
The `AppComponent.fontSizePx` establishes the initial `SizerComponent.size` value.
|
||||
|
||||
<code-example path="two-way-binding/src/app/app.component.ts" header="src/app/app.component.ts" region="font-size"></code-example>
|
||||
|
||||
Clicking the buttons updates the `AppComponent.fontSizePx` via the two-way binding.
|
||||
The revised `AppComponent.fontSizePx` value flows through to the _style_ binding,
|
||||
making the displayed text bigger or smaller.
|
||||
|
||||
The two-way binding syntax is really just syntactic sugar for a _property_ binding and an _event_ binding.
|
||||
Angular desugars the `SizerComponent` binding into this:
|
||||
|
||||
<code-example path="two-way-binding/src/app/app.component.html" header="src/app/app.component.html (two-way-2)" region="two-way-2"></code-example>
|
||||
|
||||
The `$event` variable contains the payload of the `SizerComponent.sizeChange` event.
|
||||
Angular assigns the `$event` value to the `AppComponent.fontSizePx` when the user clicks the buttons.
|
||||
|
||||
## Two-way binding in forms
|
||||
|
||||
The two-way binding syntax is a great convenience compared to
|
||||
separate property and event bindings. It would be convenient to
|
||||
use two-way binding with HTML form elements like `<input>` and
|
||||
`<select>`. However, no native HTML element follows the `x`
|
||||
value and `xChange` event pattern.
|
||||
|
||||
For more on how to use two-way binding in forms, see
|
||||
Angular [NgModel](guide/built-in-directives#ngModel).
|
@ -1,76 +1,76 @@
|
||||
# Two-way binding `[(...)]`
|
||||
# Enlace bidireccional `[(...)]`
|
||||
|
||||
Two-way binding gives your app a way to share data between a component class and
|
||||
its template.
|
||||
El enlace bidireccional le brinda a su aplicación una forma de compartir datos entre una clase de componente y la plantilla.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See the <live-example></live-example> for a working example containing the code snippets in this guide.
|
||||
Consulta el <live-example></live-example> para ver un ejemplo funcional que contiene los fragmentos de código de esta guía.
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## Basics of two-way binding
|
||||
## Conceptos básicos del enlace bidireccional
|
||||
|
||||
Two-way binding does two things:
|
||||
El enlace bidireccional hace dos cosas:
|
||||
|
||||
1. Sets a specific element property.
|
||||
1. Listens for an element change event.
|
||||
1. Establece una propiedad de elemento específica.
|
||||
1. Escucha un evento de cambio de elemento.
|
||||
|
||||
Angular offers a special _two-way data binding_ syntax for this purpose, `[()]`.
|
||||
The `[()]` syntax combines the brackets
|
||||
of property binding, `[]`, with the parentheses of event binding, `()`.
|
||||
Angular ofrece una sintaxis especial _enlace de datos bidireccional_ para este propósito, `[()]`.
|
||||
La sintaxis `[()]` combina los corchetes
|
||||
de enlace de propiedad, `[]`, con el paréntesis de vinculación de eventos, `()`.
|
||||
|
||||
<div class="callout is-important">
|
||||
|
||||
<header>
|
||||
[( )] = banana in a box
|
||||
[( )] = banana en una caja
|
||||
</header>
|
||||
|
||||
Visualize a *banana in a box* to remember that the parentheses go _inside_ the brackets.
|
||||
Visualiza una *banana en una caja* para recordar que los paréntesis van _dentro_ de los corchetes.
|
||||
|
||||
</div>
|
||||
|
||||
The `[()]` syntax is easy to demonstrate when the element has a settable
|
||||
property called `x` and a corresponding event named `xChange`.
|
||||
Here's a `SizerComponent` that fits this pattern.
|
||||
It has a `size` value property and a companion `sizeChange` event:
|
||||
La sintaxis `[()]` es fácil de demostrar cuando el elemento tiene un valor configurable
|
||||
propiedad llamada `x` y un evento correspondiente llamado `xChange`.
|
||||
Aquí hay un `SizerComponent` que se ajusta a este patrón.
|
||||
Tiene una propiedad de valor `size` y un evento acompañante `sizeChange`:
|
||||
|
||||
<code-example path="two-way-binding/src/app/sizer/sizer.component.ts" header="src/app/sizer.component.ts"></code-example>
|
||||
|
||||
<code-example path="two-way-binding/src/app/sizer/sizer.component.html" header="src/app/sizer.component.html"></code-example>
|
||||
|
||||
The initial `size` is an input value from a property binding.
|
||||
Clicking the buttons increases or decreases the `size`, within
|
||||
min/max value constraints,
|
||||
and then raises, or emits, the `sizeChange` event with the adjusted size.
|
||||
El `size` inicial es un valor de entrada de un enlace de propiedad.
|
||||
Al hacer clic en los botones, aumenta o disminuye el `size`, dentro de
|
||||
restricciones de valor mínimo/máximo,
|
||||
y luego genera, o emite, el evento `sizeChange` con el tamaño ajustado.
|
||||
|
||||
Here's an example in which the `AppComponent.fontSizePx` is two-way bound to the `SizerComponent`:
|
||||
Aquí hay un ejemplo en el que `AppComponent.fontSizePx` está enlazado en dos direcciones al `SizerComponent`:
|
||||
|
||||
<code-example path="two-way-binding/src/app/app.component.html" header="src/app/app.component.html (two-way-1)" region="two-way-1"></code-example>
|
||||
|
||||
The `AppComponent.fontSizePx` establishes the initial `SizerComponent.size` value.
|
||||
El `AppComponent.fontSizePx` establece el valor inicial de `SizerComponent.size`.
|
||||
|
||||
<code-example path="two-way-binding/src/app/app.component.ts" header="src/app/app.component.ts" region="font-size"></code-example>
|
||||
|
||||
Clicking the buttons updates the `AppComponent.fontSizePx` via the two-way binding.
|
||||
The revised `AppComponent.fontSizePx` value flows through to the _style_ binding,
|
||||
making the displayed text bigger or smaller.
|
||||
Al hacer clic en los botones, se actualiza `AppComponent.fontSizePx` a través del enlace bidireccional.
|
||||
El valor revisado de `AppComponent.fontSizePx` fluye a través del enlace _style_,
|
||||
haciendo que el texto mostrado sea más grande o más pequeño.
|
||||
|
||||
The two-way binding syntax is really just syntactic sugar for a _property_ binding and an _event_ binding.
|
||||
Angular desugars the `SizerComponent` binding into this:
|
||||
La sintaxis de enlace bidireccional es en realidad sólo azúcar sintáctica para un enlace _property_ y un enlace _event_.
|
||||
Angular quita el azúcar de el enlace `SizerComponent` en esto:
|
||||
|
||||
<code-example path="two-way-binding/src/app/app.component.html" header="src/app/app.component.html (two-way-2)" region="two-way-2"></code-example>
|
||||
|
||||
The `$event` variable contains the payload of the `SizerComponent.sizeChange` event.
|
||||
Angular assigns the `$event` value to the `AppComponent.fontSizePx` when the user clicks the buttons.
|
||||
La variable `$event` contiene la carga útil del evento `SizerComponent.sizeChange`.
|
||||
Angular asigna el valor `$event` al ʻAppComponent.fontSizePx` cuando el usuario hace clic en los botones.
|
||||
|
||||
## Two-way binding in forms
|
||||
## Enlace bidireccional en formularios
|
||||
|
||||
The two-way binding syntax is a great convenience compared to
|
||||
separate property and event bindings. It would be convenient to
|
||||
use two-way binding with HTML form elements like `<input>` and
|
||||
`<select>`. However, no native HTML element follows the `x`
|
||||
value and `xChange` event pattern.
|
||||
La sintaxis de enlace bidireccional es una gran comodidad en comparación con
|
||||
propiedades independientes y enlaces de eventos. Seria conveniente
|
||||
utilizar enlace bidireccional con elementos de formulario HTML como `<input>` y
|
||||
`<select>`. Sin embargo, ningún elemento HTML nativo sigue a el valor `x`
|
||||
y el patrón de evento `xChange`.
|
||||
|
||||
For more on how to use two-way binding in forms, see
|
||||
Para obtener más información sobre cómo utilizar la vinculación bidireccional en formularios, consulte
|
||||
Angular [NgModel](guide/built-in-directives#ngModel).
|
||||
|
58
aio/content/guide/web-worker.en.md
Normal file
58
aio/content/guide/web-worker.en.md
Normal file
@ -0,0 +1,58 @@
|
||||
# Background processing using web workers
|
||||
|
||||
[Web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) allow you to run CPU-intensive computations in a background thread,
|
||||
freeing the main thread to update the user interface.
|
||||
If you find your application performs a lot of computations, such as generating CAD drawings or doing heavy geometrical calculations, using web workers can help increase your application's performance.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The CLI does not support running Angular itself in a web worker.
|
||||
|
||||
</div>
|
||||
|
||||
## Adding a web worker
|
||||
|
||||
To add a web worker to an existing project, use the Angular CLI `ng generate` command.
|
||||
|
||||
`ng generate web-worker` *location*
|
||||
|
||||
You can add a web worker anywhere in your application.
|
||||
For example, to add a web worker to the root component, `src/app/app.component.ts`, run the following command.
|
||||
|
||||
`ng generate web-worker app`
|
||||
|
||||
The command performs the following actions.
|
||||
|
||||
- Configures your project to use web workers, if it isn't already.
|
||||
- Adds the following scaffold code to `src/app/app.worker.ts` to receive messages.
|
||||
|
||||
<code-example language="typescript" header="src/app/app.worker.ts">
|
||||
addEventListener('message', ({ data }) => {
|
||||
const response = `worker response to ${data}`;
|
||||
postMessage(response);
|
||||
});
|
||||
</code-example>
|
||||
|
||||
- Adds the following scaffold code to `src/app/app.component.ts` to use the worker.
|
||||
|
||||
<code-example language="typescript" header="src/app/app.component.ts">
|
||||
if (typeof Worker !== 'undefined') {
|
||||
// Create a new
|
||||
const worker = new Worker('./app.worker', { type: 'module' });
|
||||
worker.onmessage = ({ data }) => {
|
||||
console.log(`page got message: ${data}`);
|
||||
};
|
||||
worker.postMessage('hello');
|
||||
} else {
|
||||
// Web workers are not supported in this environment.
|
||||
// You should add a fallback so that your program still executes correctly.
|
||||
}
|
||||
</code-example>
|
||||
|
||||
After you generate this initial scaffold, you must refactor your code to use the web worker by sending messages to and from the worker.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
Some environments or platforms, such as `@angular/platform-server` used in [Server-side Rendering](guide/universal), don't support web workers. To ensure that your application will work in these environments, you must provide a fallback mechanism to perform the computations that the worker would otherwise perform.
|
||||
|
||||
</div>
|
@ -1,30 +1,30 @@
|
||||
# Background processing using web workers
|
||||
# Procesamiento en segundo plano utilizando web workers
|
||||
|
||||
[Web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) allow you to run CPU-intensive computations in a background thread,
|
||||
freeing the main thread to update the user interface.
|
||||
If you find your application performs a lot of computations, such as generating CAD drawings or doing heavy geometrical calculations, using web workers can help increase your application's performance.
|
||||
[Web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) te permiten ejecutar cálculos intensivos de CPU en un subproceso en segundo plano,
|
||||
liberando el hilo principal para actualizar la interfaz de usuario.
|
||||
Si encuentras que la aplicación realiza una gran cantidad de cálculos, como generar dibujos CAD o realizar cálculos geométricos pesados, el uso de web workers puede ayudar a aumentar el rendimiento de la aplicación.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The CLI does not support running Angular itself in a web worker.
|
||||
La CLI no admite la ejecución de Angular en un web worker.
|
||||
|
||||
</div>
|
||||
|
||||
## Adding a web worker
|
||||
## Agregando un web worker
|
||||
|
||||
To add a web worker to an existing project, use the Angular CLI `ng generate` command.
|
||||
Para agregar un web worker a un proyecto existente, utiliza el comando de Angular `ng generate` de la CLI.
|
||||
|
||||
`ng generate web-worker` *location*
|
||||
|
||||
You can add a web worker anywhere in your application.
|
||||
For example, to add a web worker to the root component, `src/app/app.component.ts`, run the following command.
|
||||
Puedes agregar un web worker en cualquier lugar de la aplicación.
|
||||
Por ejemplo, para agregar un web worker al componente raíz, `src/app/app.component.ts`, ejecuta el siguiente comando.
|
||||
|
||||
`ng generate web-worker app`
|
||||
|
||||
The command performs the following actions.
|
||||
El comando realiza las siguientes acciones.
|
||||
|
||||
- Configures your project to use web workers, if it isn't already.
|
||||
- Adds the following scaffold code to `src/app/app.worker.ts` to receive messages.
|
||||
- Configura el proyecto para que use web workers, si aún no lo está.
|
||||
- Agrega el siguiente código a `src/app/app.worker.ts` para recibir mensajes.
|
||||
|
||||
<code-example language="typescript" header="src/app/app.worker.ts">
|
||||
addEventListener('message', ({ data }) => {
|
||||
@ -33,7 +33,7 @@ The command performs the following actions.
|
||||
});
|
||||
</code-example>
|
||||
|
||||
- Adds the following scaffold code to `src/app/app.component.ts` to use the worker.
|
||||
- Agrega el siguiente código `src/app/app.component.ts` para usar el worker.
|
||||
|
||||
<code-example language="typescript" header="src/app/app.component.ts">
|
||||
if (typeof Worker !== 'undefined') {
|
||||
@ -49,10 +49,10 @@ The command performs the following actions.
|
||||
}
|
||||
</code-example>
|
||||
|
||||
After you generate this initial scaffold, you must refactor your code to use the web worker by sending messages to and from the worker.
|
||||
Después de generar esta estructura inicial, debes refactorizar el código para usar el web worker enviando mensajes desde y hacia el worker.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
Some environments or platforms, such as `@angular/platform-server` used in [Server-side Rendering](guide/universal), don't support web workers. To ensure that your application will work in these environments, you must provide a fallback mechanism to perform the computations that the worker would otherwise perform.
|
||||
Algunos entornos o plataformas, como `@angular/platform-server` utilizado en [Renderizado del lado del servidor](guide/universal), no admiten web workers. Para asegurarte de que la aplicación funcionará en estos entornos, debes proporcionar un mecanismo de reserva para realizar los cálculos que el worker realizaría de otro modo.
|
||||
|
||||
</div>
|
||||
|
@ -1,32 +1,32 @@
|
||||
# Contributors page
|
||||
# Página de colaboradores
|
||||
|
||||
We have an official accounting of who is on the Angular Team, who are "trusted collaborators" (see https://team.angular.io/collaborators), and so on.
|
||||
Tenemos una contabilidad oficial de quiénes están en el Angular Team, quiénes son "colaboradores de confianza" (consulte https://team.angular.io/collaborators), etc.
|
||||
|
||||
The `contributors.json` should be maintained to keep our "org chart" in a single consistent place.
|
||||
El `contributors.json` debe mantenerse para mantener nuestro" organigrama "en un solo lugar coherente.
|
||||
|
||||
## GDE listings
|
||||
## Lista de GDE
|
||||
|
||||
There are two pages:
|
||||
Hay dos páginas:
|
||||
|
||||
- https://developers.google.com/experts/all/technology/angular
|
||||
(Googlers: source at http://google3/googledata/devsite/content/en/experts/all/technology/angular.html)
|
||||
which is maintained by Dawid Ostrowski based on a spreadsheet
|
||||
(Empleados de Google: fuente en http://google3/googledata/devsite/content/en/experts/all/technology/angular.html)
|
||||
que es mantenido por Dawid Ostrowski basado en una hoja de cálculo
|
||||
https://docs.google.com/spreadsheets/d/1_Ls2Kle7NxPBIG8f3OEVZ4gJZ8OCTtBxGYwMPb1TUVE/edit#gid=0.
|
||||
<!-- gkalpak: That URL doesn't seem to work any more. New URL: https://developers.google.com/programs/experts/directory/ (?) -->
|
||||
|
||||
- Ours: https://angular.io/about?group=GDE which is derived from `contributors.json`.
|
||||
- Nuestro: https://angular.io/about?group=GDE que se deriva de `contributors.json`.
|
||||
|
||||
Alex Eagle is investigating how to reconcile these two lists.
|
||||
Alex Eagle está investigando cómo conciliar estas dos listas.
|
||||
|
||||
## About the data
|
||||
## Sobre los datos
|
||||
|
||||
- Keys in `contributors.json` should be GitHub handles. (Most currently are, but not all.)
|
||||
This will allow us to use GitHub as the default source for things like name, avatar, etc.
|
||||
- Pictures are stored in `aio/content/images/bios/<picture-filename>`.
|
||||
- Las llaves en `contributors.json` deben ser identificadores de GitHub. (La mayoría lo son actualmente, pero no todos).
|
||||
Esto nos permitirá usar GitHub como fuente predeterminada para cosas como nombre, avatar, etc.
|
||||
- Las imágenes se almacenan en `aio/content/images/bios/<picture-filename>`.
|
||||
|
||||
## Processing the data
|
||||
## Procesando los datos
|
||||
|
||||
Install https://stedolan.github.io/jq/ which is amazing.
|
||||
Instala https://stedolan.github.io/jq/ que es increíble.
|
||||
|
||||
```sh
|
||||
for handle in $(jq keys[] --raw-output < aio/content/marketing/contributors.json)
|
||||
@ -35,4 +35,4 @@ do echo -e "\n$handle\n---------\n"; curl --silent -H "Authorization: token ${TO
|
||||
done
|
||||
```
|
||||
|
||||
Relevant scripts are stored in `aio/scripts/contributors/`.
|
||||
Los scripts relevantes se almacenan en `aio/scripts/contributors/`.
|
||||
|
@ -1,9 +1,9 @@
|
||||
<h1 class="title center no-toc">Angular Contributors</h1>
|
||||
<h2>Building For the Future</h2>
|
||||
<h1 class="title center no-toc">Colaboradores de Angular</h1>
|
||||
<h2>Construyendo para el futuro</h2>
|
||||
<p>
|
||||
Angular is built by a team of engineers who share a passion for making web development feel
|
||||
effortless. We believe that writing beautiful apps should be joyful and fun. We're building a
|
||||
platform for the future.
|
||||
Angular está construido por un equipo de ingenieros que comparten la pasión por hacer que el desarrollo web se sienta
|
||||
fácil. Creemos que escribir aplicaciones hermosas debe ser placentero y divertido. Estamos construyendo una
|
||||
plataforma para el futuro.
|
||||
</p>
|
||||
|
||||
<aio-contributor-list></aio-contributor-list>
|
||||
|
53
aio/content/marketing/analytics.en.md
Normal file
53
aio/content/marketing/analytics.en.md
Normal file
@ -0,0 +1,53 @@
|
||||
# Usage Metrics Gathering
|
||||
You can help the Angular Team to prioritize features and improvements by permitting the Angular
|
||||
team to send command-line command usage statistics to Google. The Angular Team does not collect
|
||||
usage statistics unless you explicitly opt in during the Angular CLI installation or upgrade.
|
||||
|
||||
## What is collected?
|
||||
Usage analytics include the commands and selected flags for each execution. Usage analytics may
|
||||
include the following information:
|
||||
|
||||
- Your operating system (Mac, Linux distribution, Windows) and its version.
|
||||
- Number of CPUs, amount of RAM.
|
||||
- Node and Angular CLI version (local version only).
|
||||
- How long each command took to initialize and execute.
|
||||
- Command name that was run.
|
||||
- For Schematics commands (add, generate, new and update), a list of selected flags.
|
||||
- For build commands (build, serve), the number and size of bundles (initial and lazy),
|
||||
compilation units, the time it took to build and rebuild, and basic Angular-specific
|
||||
API usage.
|
||||
- Error code of exceptions and crash data. No stack trace is collected.
|
||||
|
||||
Only Angular owned and developed schematics and builders are reported. Third-party schematics and
|
||||
builders do not send data to the Angular Team.
|
||||
|
||||
## Opting in
|
||||
When installing the Angular CLI or upgrading an existing version, you are prompted to allow global
|
||||
collection of usage statistics. If you say no or skip the prompt, no data is collected.
|
||||
|
||||
Starting with version 8, we added the `analytics` command to the CLI. You can change your opt-in
|
||||
decision at any time using this command.
|
||||
|
||||
### Disabling usage analytics
|
||||
To disable analytics gathering, run the following command:
|
||||
|
||||
```bash
|
||||
# Disable all usage analytics.
|
||||
ng analytics off
|
||||
```
|
||||
|
||||
### Enabling usage analytics
|
||||
To enable usage analytics, run the following command:
|
||||
|
||||
```bash
|
||||
# Enable all usage analytics.
|
||||
ng analytics on
|
||||
```
|
||||
|
||||
### Prompting
|
||||
To prompt the user again about usage analytics, run the following command:
|
||||
|
||||
```bash
|
||||
# Prompt for all usage analytics.
|
||||
ng analytics prompt
|
||||
```
|
@ -1,51 +1,48 @@
|
||||
# Usage Metrics Gathering
|
||||
You can help the Angular Team to prioritize features and improvements by permitting the Angular
|
||||
team to send command-line command usage statistics to Google. The Angular Team does not collect
|
||||
usage statistics unless you explicitly opt in during the Angular CLI installation or upgrade.
|
||||
# Recopilación de métricas de uso
|
||||
Puede ayudar al equipo de Angular a priorizar funciones y mejoras al permitir el equipo de Angular pueda enviar estadísticas de uso de comandos del cli más utilizados a Google. El equipo de Angular no recolecta
|
||||
estadísticas de uso a menos que aceptes compartir esta información durante la instalación o actualización de Angular CLI.
|
||||
|
||||
## What is collected?
|
||||
Usage analytics include the commands and selected flags for each execution. Usage analytics may
|
||||
include the following information:
|
||||
## ¿Qué se recolecta?
|
||||
El análisis de uso incluye los comandos y las banderas seleccionadas para cada ejecución. El análisis de uso puede
|
||||
incluye la siguiente información:
|
||||
|
||||
- Your operating system (Mac, Linux distribution, Windows) and its version.
|
||||
- Number of CPUs, amount of RAM.
|
||||
- Node and Angular CLI version (local version only).
|
||||
- How long each command took to initialize and execute.
|
||||
- Command name that was run.
|
||||
- For Schematics commands (add, generate, new and update), a list of whitelisted flags.
|
||||
- For build commands (build, serve), the number and size of bundles (initial and lazy),
|
||||
compilation units, the time it took to build and rebuild, and basic Angular-specific
|
||||
API usage.
|
||||
- Error code of exceptions and crash data. No stack trace is collected.
|
||||
- Su sistema operativo (Mac, distribución de Linux, Windows) y su versión.
|
||||
- Número de CPU, cantidad de RAM.
|
||||
- Versión CLI de Node y Angular (solo versión local).
|
||||
- Cuánto tiempo tardó cada comando en inicializarse y ejecutarse.
|
||||
- Nombre del comando que se ejecutó.
|
||||
- Para los comandos de Schematics (add, generate, new y update), una lista de banderas en la lista blanca.
|
||||
- Para los comandos de compilación (build, serve), la cantidad y el tamaño de los paquetes (initial y lazy),
|
||||
unidades de compilación, el tiempo que tomó compilar y reconstruir, y las unidades básicas específicas de Angular
|
||||
Uso de API.
|
||||
- Código de error de excepciones y datos de fallos. No se recopila ningún rastro de pila.
|
||||
|
||||
Only Angular owned and developed schematics and builders are reported. Third-party schematics and
|
||||
builders do not send data to the Angular Team.
|
||||
Solo se informan los schematics y builders desarrollados y de propiedad de Angular. Schematics y Builders de terceros no envían datos al equipo de Angular.
|
||||
|
||||
## Opting in
|
||||
When installing the Angular CLI or upgrading an existing version, you are prompted to allow global
|
||||
collection of usage statistics. If you say no or skip the prompt, no data is collected.
|
||||
## Participar
|
||||
Al instalar Angular CLI o actualizar una versión existente, se le solicitara que permita la recopilación de estadísticas de uso de manera global. Si dice que no u omite la indicación, no se recopilan datos.
|
||||
|
||||
Starting with version 8, we added the `analytics` command to the CLI. You can change your opt-in
|
||||
decision at any time using this command.
|
||||
Comenzando con la versión 8, agregamos el comando `analytics` a la CLI. Puede cambiar su suscripción
|
||||
decisión en cualquier momento utilizando este comando.
|
||||
|
||||
### Disabling usage analytics
|
||||
To disable analytics gathering, run the following command:
|
||||
### Desactivación de análisis de uso
|
||||
Para deshabilitar la recopilación de análisis, ejecute el siguiente comando:
|
||||
|
||||
```bash
|
||||
# Disable all usage analytics.
|
||||
ng analytics off
|
||||
```
|
||||
|
||||
### Enabling usage analytics
|
||||
To enable usage analytics, run the following command:
|
||||
### Habilitación de análisis de uso
|
||||
Para habilitar el análisis de uso, ejecute el siguiente comando:
|
||||
|
||||
```bash
|
||||
# Enable all usage analytics.
|
||||
ng analytics on
|
||||
```
|
||||
|
||||
### Prompting
|
||||
To prompt the user again about usage analytics, run the following command:
|
||||
### Volver a mostrar aviso de Analiticas
|
||||
Para volver a preguntar al usuario sobre el análisis de uso, ejecute el siguiente comando:
|
||||
|
||||
```bash
|
||||
# Prompt for all usage analytics.
|
||||
|
@ -1,54 +1,53 @@
|
||||
<header class="marketing-banner">
|
||||
<h1 class="banner-headline no-toc no-anchor">Contribute to Angular</h1>
|
||||
<h1 class="banner-headline no-toc no-anchor">Contribuir a Angular</h1>
|
||||
</header>
|
||||
|
||||
<article class="contribute-container">
|
||||
<h2 class="no-anchor">Angular Projects</h2>
|
||||
<h2 class="no-anchor">Proyectos Angular</h2>
|
||||
|
||||
<p>We'd love for you to contribute to our source code and to make Angular projects even better.</p>
|
||||
<p>Nos encantaría que contribuyas a nuestro código fuente y que hicieras los proyectos de Angular aún mejores.</p>
|
||||
|
||||
<div class="card-section">
|
||||
<div>
|
||||
<h3 class="no-anchor">Angular</h3>
|
||||
|
||||
Angular is a next generation mobile and desktop application development platform.
|
||||
|
||||
Angular es una plataforma de desarrollo de aplicaciones móviles y de escritorio de próxima generación.
|
||||
</div>
|
||||
<a href="https://github.com/angular/angular/blob/master/CONTRIBUTING.md" class="button button-blue" md-button>Contribute</a>
|
||||
<a href="https://github.com/angular/angular/blob/master/CONTRIBUTING.md" class="button button-blue" md-button>Contribuir</a>
|
||||
</div>
|
||||
|
||||
<div class="card-section">
|
||||
<div>
|
||||
<h3 class="no-anchor">Angular CLI</h3>
|
||||
|
||||
Angular CLI makes it easy to create an application that already works, right out of the box. It already follows our best practices.
|
||||
Angular CLI facilita la creación de una aplicación que funciona desde el primer momento. Ya sigue nuestras mejores prácticas.
|
||||
|
||||
</div>
|
||||
|
||||
<a href="https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md" class="button button-blue" md-button>Contribute</a>
|
||||
<a href="https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md" class="button button-blue" md-button>Contribuir</a>
|
||||
</div>
|
||||
|
||||
<div class="card-section">
|
||||
<div>
|
||||
<h3 class="no-anchor">Angular Material</h3>
|
||||
|
||||
Our goal is to deliver a lean, lightweight set of Angular-based UI elements that implement the material design specification
|
||||
for use in Angular single-page applications (SPAs).
|
||||
Nuestro objetivo es ofrecer un conjunto delgado y liviano de elementos de UI basados en Angular que implementen la especificación de diseño de material.
|
||||
para su uso en aplicaciones Angular de una sola página (SPA).
|
||||
|
||||
</div>
|
||||
|
||||
<a href="https://github.com/angular/material2/blob/master/CONTRIBUTING.md" class="button button-blue" md-button>Contribute</a>
|
||||
<a href="https://github.com/angular/material2/blob/master/CONTRIBUTING.md" class="button button-blue" md-button>Contribuir</a>
|
||||
</div>
|
||||
|
||||
<div class="card-section">
|
||||
<div>
|
||||
<h3 class="no-anchor">AngularFire</h3>
|
||||
|
||||
AngularFire is the officially supported Angular binding for Firebase. Firebase is a full backend so you don't need servers
|
||||
to build your Angular app.
|
||||
AngularFire es el enlace Angular oficialmente compatible para Firebase. Firebase es un backend completo, por lo que no necesita servidores
|
||||
para construir su aplicación Angular.
|
||||
|
||||
</div>
|
||||
<a href="https://github.com/angular/angularfire2/blob/master/CONTRIBUTING.md" class="button button-blue" md-button> Contribute</a>
|
||||
<a href="https://github.com/angular/angularfire2/blob/master/CONTRIBUTING.md" class="button button-blue" md-button> Contribuir</a>
|
||||
</div>
|
||||
|
||||
</article>
|
||||
|
@ -272,7 +272,7 @@
|
||||
"website": "https://www.softwarearchitekt.at",
|
||||
"bio": "Trainer and Consultant with focus on Angular. Writes for O'Reilly, the German Java Magazine and Heise. Regularly speaks at conferences.",
|
||||
"mentor": "mgechev",
|
||||
"groups": ["GDE", "Collaborators"]
|
||||
"groups": ["GDE", "Colaboradores"]
|
||||
},
|
||||
"maximsalnikov": {
|
||||
"name": "Maxim Salnikov",
|
||||
@ -549,7 +549,7 @@
|
||||
"twitter": "samjulien",
|
||||
"website": "http://www.samjulien.com/",
|
||||
"bio": "Sam Julien builds software, articles, video courses, and campfires. A developer, speaker, writer, and GDE in the Pacific Northwest, Sam's favorite thing in the world is changing someone's life by teaching them to code.",
|
||||
"groups": ["Collaborators", "GDE"],
|
||||
"groups": ["Colaboradores", "GDE"],
|
||||
"mentor": "gkalpak"
|
||||
},
|
||||
"tracylee": {
|
||||
@ -562,7 +562,7 @@
|
||||
},
|
||||
"jiali": {
|
||||
"name": "Jia Li",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"mentor": "mhevery",
|
||||
"picture": "JiaLiPassion.jpg",
|
||||
"twitter": "Jialipassion",
|
||||
@ -572,32 +572,32 @@
|
||||
"cexbrayat": {
|
||||
"name": "Cédric Exbrayat",
|
||||
"mentor": "petebacondarwin",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"picture": "cexbrayat.jpg",
|
||||
"bio": "Author of `Become a ninja with Angular (2+)` https://books.ninja-squad.com/angular - Angular trainer and @Ninja-Squad co-founder"
|
||||
},
|
||||
"ajitsinghkaler": {
|
||||
"name": "Ajit Singh",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"picture": "ajitsinghkaler.jpg",
|
||||
"twitter": "ajitsinghkaler",
|
||||
"bio": "Software Engineer in Bangalore, India who loves to learn something new and is interested in front end technologies"
|
||||
},
|
||||
"CaerusKaru": {
|
||||
"name": "Adam Plumer",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"mentor": "vikerman",
|
||||
"picture": "CaerusKaru.jpg"
|
||||
},
|
||||
"jbedard": {
|
||||
"name": "Jason Bedard",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"mentor": "kyliau",
|
||||
"picture": "jbedard.jpg"
|
||||
},
|
||||
"JoostK": {
|
||||
"name": "Joost Koehoorn",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"mentor": "alxhub",
|
||||
"picture": "joostk.jpg",
|
||||
"twitter": "devjoost",
|
||||
@ -605,7 +605,7 @@
|
||||
},
|
||||
"sonukapoor": {
|
||||
"name": "Sonu Kapoor",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"picture": "sonukapoor.jpg",
|
||||
"website": "https://www.linkedin.com/in/sonu-kapoor/",
|
||||
"bio": "Sonu is a Software Engineer from Toronto, with a high interest in front-end technologies and algorithms."
|
||||
@ -702,7 +702,7 @@
|
||||
},
|
||||
"ayazhafiz": {
|
||||
"name": "Ayaz Hafiz",
|
||||
"groups": ["Collaborators"],
|
||||
"groups": ["Colaboradores"],
|
||||
"picture": "hafiz.jpg",
|
||||
"website": "https://github.com/ayazhafiz",
|
||||
"bio": "Ayaz is an undergraduate student with interests in free software."
|
||||
|
@ -3,7 +3,7 @@
|
||||
Angular es un framework de diseño de aplicaciones y plataforma de desarrollo para crear aplicaciones de una
|
||||
sola página eficientes y sofisticadas
|
||||
|
||||
Esta documentación de Angular te ayuda a aprender y usar el framework y la plataforma de desarrollo, desde su
|
||||
Esta documentación de Angular te ayuda a aprender y usar el framework y la plataforma de desarrollo, desde tu
|
||||
primera aplicación hasta la optimización de aplicaciones complejas de una sola página, para empresas.
|
||||
Los tutoriales y guías incluyen ejemplos descargables para acelerar tus proyectos.
|
||||
|
||||
@ -38,14 +38,14 @@ Los tutoriales y guías incluyen ejemplos descargables para acelerar tus proyect
|
||||
## Supuestos
|
||||
|
||||
|
||||
Esta documentación asume que estas familiarizado con
|
||||
Esta documentación asume que estás familiarizado con
|
||||
[HTML](https://developer.mozilla.org/es/docs/Learn/HTML/Introduccion_a_HTML "Aprende HTML"),
|
||||
[CSS](https://developer.mozilla.org/es/docs/Learn/CSS/First_steps "Aprende CSS"),
|
||||
[JavaScript](https://developer.mozilla.org/es/docs/Web/JavaScript/Una_re-introducci%C3%B3n_a_JavaScript "Aprende JavaScript"),
|
||||
y algunas herramientas de los
|
||||
[últimos estándares javascript](https://developer.mozilla.org/es/docs/Web/JavaScript/Language_Resources "Últimos estándares JavaScript"),
|
||||
como son las [clases](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Classes "Clases ES2015")
|
||||
y [modulos](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Sentencias/import "Modulos ES2015").
|
||||
y [módulos](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Sentencias/import "Modulos ES2015").
|
||||
Los ejemplos de código son escritos usando [TypeScript](https://www.typescriptlang.org/ "TypeScript").
|
||||
La mayor parte del código Angular se puede escribir tan solo con la versión más reciente de JavaScript, usando
|
||||
[tipos](https://www.typescriptlang.org/docs/handbook/classes.html "Tipos TypeScript") para inyección de
|
||||
@ -55,7 +55,7 @@ para metadatos.
|
||||
|
||||
## Retrolimentación
|
||||
|
||||
<h3>Puedes sentarte con nosotros!</h3>
|
||||
<h3>¡Puedes sentarte con nosotros!</h3>
|
||||
|
||||
Queremos saber de ti.
|
||||
[Informa problemas o envía sugerencias para nueva documentación.](https://github.com/angular-hispano/angular/issues/new/choose "Repositorio GitHub de Angular, form para nuevo issue")
|
||||
@ -67,5 +67,5 @@ Mira [Colaborando a Angular](https://github.com/angular-hispano/angular/blob/mas
|
||||
para obtener información sobre las pautas de envío de nuevas colaboraciones.
|
||||
|
||||
Nuestra comunidad valora la comunicación respetuosa y solidaria.
|
||||
Consulta y adhierete al
|
||||
Consulta y adhiérete al
|
||||
[Código de Conducta](https://angular.lat/coc "Código de Conducta del comunidad").
|
||||
|
@ -3,26 +3,26 @@
|
||||
</header>
|
||||
|
||||
<article class="events-container">
|
||||
<p>Where we'll be presenting:</p>
|
||||
<p>Dónde estaremos presentando:</p>
|
||||
<table class="is-full-width">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Event</th>
|
||||
<th>Location</th>
|
||||
<th>Date</th>
|
||||
<th>Evento</th>
|
||||
<th>Ubicación</th>
|
||||
<th>Fecha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p>Where we already presented:</p>
|
||||
<p>Eventos Pasados:</p>
|
||||
<table class="is-full-width">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Event</th>
|
||||
<th>Location</th>
|
||||
<th>Date</th>
|
||||
<th>Eventos</th>
|
||||
<th>Ubicación</th>
|
||||
<th>Fecha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
@ -1,5 +1,5 @@
|
||||
<header class="marketing-banner">
|
||||
<h1 class="banner-headline no-toc no-anchor">Features & Benefits</h1>
|
||||
<h1 class="banner-headline no-toc no-anchor">Funcionalidades y Ventajas</h1>
|
||||
</header>
|
||||
|
||||
<article>
|
||||
@ -7,25 +7,28 @@
|
||||
<div>
|
||||
<div class="feature-section">
|
||||
<div class="feature-header">
|
||||
<div class="text-headline">Cross Platform</div>
|
||||
<div class="text-headline">Multiplataforma</div>
|
||||
<img src="generated/images/marketing/features/feature-icon.svg" height="70px" alt="">
|
||||
</div>
|
||||
<div class="feature-row">
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Progressive Web Apps</div>
|
||||
<p class="text-body">Use modern web platform capabilities to deliver app-like experiences.
|
||||
High performance, offline, and zero-step installation.</p>
|
||||
<div class="feature-title">Aplicaciones Web Progresivas "PWA"</div>
|
||||
<p class="text-body">Utiliza las capacidades modernas de la plataforma web para ofrecer experiencias
|
||||
similares a las de las aplicaciones.
|
||||
Instalación de alto rendimiento, sin conexión y en cero pasos.</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Native</div>
|
||||
<p class="text-body">Build native mobile apps with strategies from Cordova, Ionic, or NativeScript.</p>
|
||||
<div class="feature-title">Nativo</div>
|
||||
<p class="text-body">Crea aplicaciones móviles nativas con estrategias de Cordova, Ionic o NativeScript.</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Desktop</div>
|
||||
<p class="text-body">Create desktop-installed apps across Mac, Windows, and Linux using the same Angular methods you've learned for the web plus the ability to access native OS APIs.</p>
|
||||
<div class="feature-title">Escritorio</div>
|
||||
<p class="text-body">Crea aplicaciones instaladas en el escritorio en Mac, Windows y Linux con los mismos
|
||||
métodos Angular que has aprendido para la web, además de la capacidad de acceder a las APIs nativas del
|
||||
sistema operativo.</p>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
@ -33,24 +36,30 @@
|
||||
|
||||
<div class="feature-section">
|
||||
<div class="feature-header">
|
||||
<div class="text-headline">Speed and Performance</div>
|
||||
<div class="text-headline">Velocidad y Rendimiento</div>
|
||||
<img src="generated/images/marketing/features/feature-icon.svg" height="70px" alt="">
|
||||
</div>
|
||||
<div class="feature-row">
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Code Generation</div>
|
||||
<p class="text-body">Angular turns your templates into code that's highly optimized for today's JavaScript virtual machines, giving you all the benefits of hand-written code with the productivity of a framework.</p>
|
||||
<div class="feature-title">Generación de código</div>
|
||||
<p class="text-body">Angular convierte sus plantillas en código altamente optimizado para las máquinas
|
||||
virtuales JavaScript de hoy en día, lo que le ofrece todas las ventajas del código escrito a mano con la
|
||||
productividad de un framework.</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Universal</div>
|
||||
<p class="text-body">Serve the first view of your application on Node.js®, .NET, PHP, and other servers for near-instant rendering in just HTML and CSS. Also paves the way for sites that optimize for SEO.</p>
|
||||
<p class="text-body">Sirve la primera vista de tu aplicación en Node.js®, .NET, PHP y otros servidores para
|
||||
una representación casi instantánea en HTML y CSS. También allana el camino para sitios que optimizan para
|
||||
SEO.</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Code Splitting</div>
|
||||
<p class="text-body">Angular apps load quickly with the new Component Router, which delivers automatic code-splitting so users only load code required to render the view they request.</p>
|
||||
<div class="feature-title">División de código</div>
|
||||
<p class="text-body">Las aplicaciones de Angular se cargan rápidamente con el nuevo enrutador de
|
||||
componentes, que ofrece división automática de código para que los usuarios solo carguen el código
|
||||
necesario para representar la vista que solicitan.</p>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
@ -58,24 +67,27 @@
|
||||
|
||||
<div class="feature-section">
|
||||
<div class="feature-header">
|
||||
<div class="text-headline">Productivity</div>
|
||||
<div class="text-headline">Productividad</div>
|
||||
<img src="generated/images/marketing/features/feature-icon.svg" height="70px" alt="">
|
||||
</div>
|
||||
<div class="feature-row">
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Templates</div>
|
||||
<p class="text-body">Quickly create UI views with simple and powerful template syntax.</p>
|
||||
<div class="feature-title">Plantillas</div>
|
||||
<p class="text-body">Crea rápidamente vistas de interfaz de usuario con una sintaxis de plantilla sencilla y
|
||||
potente.</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Angular CLI</div>
|
||||
<p class="text-body">Command line tools: start building fast, add components and tests, then instantly deploy.</p>
|
||||
<p class="text-body">Herramienta de linea de comando: empieza a construir rápidamente, agregar componentes
|
||||
y pruebas, luego implementar instantáneamente.</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">IDEs</div>
|
||||
<p class="text-body">Get intelligent code completion, instant errors, and other feedback in popular editors and IDEs.</p>
|
||||
<p class="text-body">Obtén la finalización inteligente del código, errores instantáneos y otros comentarios
|
||||
en editores e IDE populares.</p>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
@ -83,24 +95,28 @@
|
||||
|
||||
<div class="feature-section">
|
||||
<div class="feature-header">
|
||||
<div class="text-headline">Full Development Story</div>
|
||||
<div class="text-headline">Historia De Desarrollo Completo</div>
|
||||
<img src="generated/images/marketing/features/feature-icon.svg" height="70px" alt="">
|
||||
</div>
|
||||
<div class="feature-row">
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Testing</div>
|
||||
<p class="text-body">With Karma for unit tests, you can know if you've broken things every time you save. And Protractor makes your scenario tests run faster and in a stable manner.</p>
|
||||
<div class="feature-title">Pruebas</div>
|
||||
<p class="text-body">Con Karma para pruebas unitarias, puedes saber si has roto las cosas cada vez que
|
||||
ahorras. Y Protractor hace que sus pruebas de escenario se ejecuten más rápido y de una manera estable.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Animation</div>
|
||||
<p class="text-body">Create high-performance, complex choreographies and animation timelines with very little code through Angular's intuitive API.</p>
|
||||
<p class="text-body">Crea coreografías complejas y de alto rendimiento y líneas de tiempo de animación con
|
||||
muy poco código a través de la API intuitiva de Angular.</p>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<div class="feature-title">Accessibility</div>
|
||||
<p class="text-body">Create accessible applications with ARIA-enabled components, developer guides, and built-in a11y test infrastructure.</p>
|
||||
<div class="feature-title">Accesibilidad</div>
|
||||
<p class="text-body">Crea aplicaciones accesibles con componentes habilitados para ARIA, guías para
|
||||
desarrolladores e infraestructura de prueba a11y integrada.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -108,7 +124,7 @@
|
||||
</div>
|
||||
|
||||
<div class="cta-bar announcement-bar">
|
||||
<a class="button" href="start">Get Started</a>
|
||||
<a class="button" href="start">Introducción</a>
|
||||
</div>
|
||||
|
||||
</article>
|
||||
|
@ -1,18 +1,19 @@
|
||||
<header class="marketing-banner">
|
||||
<h1 class="banner-headline no-toc no-anchor">Press kit</h1>
|
||||
<h1 class="banner-headline no-toc no-anchor">Carpeta de prensa</h1>
|
||||
</header>
|
||||
|
||||
<article class="presskit-container">
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div>
|
||||
<h2>ANGULAR LOGO</h2>
|
||||
<h2>LOGO DE ANGULAR</h2>
|
||||
<p>
|
||||
The logo graphics available for download on this page are provided under
|
||||
Los gráficos del logotipo disponibles para descargar en esta página se proporcionan en
|
||||
<a class="cc-by-anchor" href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.
|
||||
This means that you can pretty much do what you like with it including printing it on shirts, creating your own variations, or getting it tattooed over your navel.
|
||||
Esto significa que puedes hacer lo que quieras con él, incluso imprimirlo en camisetas, crear tu
|
||||
propias variaciones, o tatuártelo sobre el ombligo.
|
||||
</p>
|
||||
<p>We do ask that you not use the rest of the site graphics in other contexts to avoid confusion.</p>
|
||||
<p>Te pedimos que no utilices el resto de los gráficos del sitio en otros contextos para evitar confusiones.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -23,13 +24,15 @@
|
||||
<img src="assets/images/logos/angular/angular.svg" alt="Full color logo Angular">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">FULL COLOR LOGO</h3>
|
||||
<h3 class="l-space-left-3">LOGOTIPO A TODO COLOR</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Angular Logo (png) - <a href="assets/images/logos/angular/angular.png" download>Download</a></span>
|
||||
<span>Logo de Angular (png) - <a href="assets/images/logos/angular/angular.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Angular Logo (svg) - <a href="assets/images/logos/angular/angular.svg" download>Download</a></span>
|
||||
<span>Logo de Angular (svg) - <a href="assets/images/logos/angular/angular.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -44,13 +47,15 @@
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">ONE COLOR LOGO</h3>
|
||||
<h3 class="l-space-left-3">LOGOTIPO DE UN COLOR</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Angular Logo Black (png) - <a href="assets/images/logos/angular/angular_solidBlack.png" download>Download</a></span>
|
||||
<span>Logo Angular en Negro (png) - <a href="assets/images/logos/angular/angular_solidBlack.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Angular Logo Black (svg) - <a href="assets/images/logos/angular/angular_solidBlack.svg" download>Download</a></span>
|
||||
<span>Logo Angular en Negro (svg) - <a href="assets/images/logos/angular/angular_solidBlack.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -61,17 +66,20 @@
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<div>
|
||||
<img src="assets/images/logos/angular/angular_whiteTransparent.svg" class="transparent-img-bg" alt="Transparent logo Angular">
|
||||
<img src="assets/images/logos/angular/angular_whiteTransparent.svg" class="transparent-img-bg"
|
||||
alt="Transparent logo Angular">
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">ONE COLOR INVERSE LOGO</h3>
|
||||
<h3 class="l-space-left-3">LOGOTIPO INVERSO DE UN COLOR</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Angular Logo White Semi-Transparent (png) - <a href="assets/images/logos/angular/angular_whiteTransparent.png" download>Download</a></span>
|
||||
<span>Logo de Angular Blanco Semi-Transparente (png) - <a
|
||||
href="assets/images/logos/angular/angular_whiteTransparent.png" download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Angular Logo Semi-Transparent (svg) - <a href="assets/images/logos/angular/angular_whiteTransparent.svg" download>Download</a></span>
|
||||
<span>Logo Angular Semi-Transparente (svg) - <a
|
||||
href="assets/images/logos/angular/angular_whiteTransparent.svg" download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -81,7 +89,7 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div>
|
||||
<h2>BRAND ICONS</h2>
|
||||
<h2>ICONOS DE MARCA</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -89,16 +97,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/animations.png" alt="Animations Icon">
|
||||
<img src="generated/images/marketing/concept-icons/animations.png" alt="Icono de Animaciones">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">ANIMATIONS</h3>
|
||||
<h3 class="l-space-left-3">ANIMACIONES</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Animations Icon (png) - <a href="generated/images/marketing/concept-icons/animations.png" download>Download</a></span>
|
||||
<span>Icono de Animaciones (png) - <a href="generated/images/marketing/concept-icons/animations.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Animations Icon (svg) - <a href="generated/images/marketing/concept-icons/animations.svg" download>Download</a></span>
|
||||
<span>Icono de Animaciones (svg) - <a href="generated/images/marketing/concept-icons/animations.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -108,16 +118,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/augury.png" alt="Augury Icon">
|
||||
<img src="generated/images/marketing/concept-icons/augury.png" alt="Icono de Augury">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">AUGURY</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Augury Icon (png) - <a href="generated/images/marketing/concept-icons/augury.png" download>Download</a></span>
|
||||
<span>Icono de Augury (png) - <a href="generated/images/marketing/concept-icons/augury.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Augury Icon (svg) - <a href="generated/images/marketing/concept-icons/augury.svg" download>Download</a></span>
|
||||
<span>Icono de Augury (svg) - <a href="generated/images/marketing/concept-icons/augury.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -127,16 +139,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/cdk.png" alt="CDK Icon">
|
||||
<img src="generated/images/marketing/concept-icons/cdk.png" alt="Icono de CDK">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">COMPONENT DEV KIT (CDK)</h3>
|
||||
<h3 class="l-space-left-3">KIT DE DESARROLLO DE COMPONENTES (CDK)</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>CDK Icon (png) - <a href="generated/images/marketing/concept-icons/cdk.png" download>Download</a></span>
|
||||
<span>Icono de CDK (png) - <a href="generated/images/marketing/concept-icons/cdk.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>CDK Icon (svg) - <a href="generated/images/marketing/concept-icons/cdk.svg" download>Download</a></span>
|
||||
<span>Icono de CDK (svg) - <a href="generated/images/marketing/concept-icons/cdk.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -146,16 +160,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/cli.png" alt="CLI Icon">
|
||||
<img src="generated/images/marketing/concept-icons/cli.png" alt="Icono de el CLI">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">CLI</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>CLI Icon (png) - <a href="generated/images/marketing/concept-icons/cli.png" download>Download</a></span>
|
||||
<span>Icono de el CLI (png) - <a href="generated/images/marketing/concept-icons/cli.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>CLI Icon (svg) - <a href="generated/images/marketing/concept-icons/cli.svg" download>Download</a></span>
|
||||
<span>Icono de el CLI (svg) - <a href="generated/images/marketing/concept-icons/cli.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -165,16 +181,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/compiler.png" alt="Compiler Icon">
|
||||
<img src="generated/images/marketing/concept-icons/compiler.png" alt="Icono de Compilador">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">COMPILER</h3>
|
||||
<h3 class="l-space-left-3">COMPILADOR</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Compiler Icon (png) - <a href="generated/images/marketing/concept-icons/compiler.png" download>Download</a></span>
|
||||
<span>Icono de Compilador (png) - <a href="generated/images/marketing/concept-icons/compiler.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Compiler Icon (svg) - <a href="generated/images/marketing/concept-icons/compiler.svg" download>Download</a></span>
|
||||
<span>Icono de Compilador (svg) - <a href="generated/images/marketing/concept-icons/compiler.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -184,16 +202,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/components.png" alt="Components Icon">
|
||||
<img src="generated/images/marketing/concept-icons/components.png" alt="Icono de Componentes Web">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">WEB COMPONENTS</h3>
|
||||
<h3 class="l-space-left-3">COMPONENTES WEB</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Web Components Icon (png) - <a href="generated/images/marketing/concept-icons/components.png" download>Download</a></span>
|
||||
<span>Icono de Componentes Web (png) - <a href="generated/images/marketing/concept-icons/components.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Web Components Icon (svg) - <a href="generated/images/marketing/concept-icons/components.svg" download>Download</a></span>
|
||||
<span>Icono de Componentes Web (svg) - <a href="generated/images/marketing/concept-icons/components.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -203,16 +223,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/forms.png" alt="Forms Icon">
|
||||
<img src="generated/images/marketing/concept-icons/forms.png" alt="Icono de Formularios">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">FORMS</h3>
|
||||
<h3 class="l-space-left-3">FORMULARIOS</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Forms Icon (png) - <a href="generated/images/marketing/concept-icons/forms.png" download>Download</a></span>
|
||||
<span>Icono de Formularios (png) - <a href="generated/images/marketing/concept-icons/forms.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Forms Icon (svg) - <a href="generated/images/marketing/concept-icons/forms.svg" download>Download</a></span>
|
||||
<span>Icono de Formularios (svg) - <a href="generated/images/marketing/concept-icons/forms.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -222,16 +244,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/http.png" alt="HTTP Icon">
|
||||
<img src="generated/images/marketing/concept-icons/http.png" alt="Icono de HTTP">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">HTTP</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>HTTP Icon (png) - <a href="generated/images/marketing/concept-icons/http.png" download>Download</a></span>
|
||||
<span>Icono de HTTP (png) - <a href="generated/images/marketing/concept-icons/http.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>HTTP Icon (svg) - <a href="generated/images/marketing/concept-icons/http.svg" download>Download</a></span>
|
||||
<span>Icono de HTTP (svg) - <a href="generated/images/marketing/concept-icons/http.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -241,16 +265,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/i18n.png" alt="i18n Icon">
|
||||
<img src="generated/images/marketing/concept-icons/i18n.png" alt="Icono de i18n">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">i18n</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>HTTP Icon (png) - <a href="generated/images/marketing/concept-icons/i18n.png" download>Download</a></span>
|
||||
<span>Icono de i18n (png) - <a href="generated/images/marketing/concept-icons/i18n.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>HTTP Icon (svg) - <a href="generated/images/marketing/concept-icons/i18n.svg" download>Download</a></span>
|
||||
<span>Icono de i18n (svg) - <a href="generated/images/marketing/concept-icons/i18n.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -260,16 +286,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/karma.png" alt="Karma Icon">
|
||||
<img src="generated/images/marketing/concept-icons/karma.png" alt="Icono de Karma">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">KARMA</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Karma Icon (png) - <a href="generated/images/marketing/concept-icons/karma.png" download>Download</a></span>
|
||||
<span>Icono de Karma (png) - <a href="generated/images/marketing/concept-icons/karma.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Karma Icon (svg) - <a href="generated/images/marketing/concept-icons/karma.svg" download>Download</a></span>
|
||||
<span>Icono de Karma (svg) - <a href="generated/images/marketing/concept-icons/karma.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -279,16 +307,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/labs.png" alt="Labs Icon">
|
||||
<img src="generated/images/marketing/concept-icons/labs.png" alt="Icono de Labs">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">LABS</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Labs Icon (png) - <a href="generated/images/marketing/concept-icons/labs.png" download>Download</a></span>
|
||||
<span>Icono de Labs (png) - <a href="generated/images/marketing/concept-icons/labs.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Labs Icon (svg) - <a href="generated/images/marketing/concept-icons/labs.svg" download>Download</a></span>
|
||||
<span>Icono de Labs (svg) - <a href="generated/images/marketing/concept-icons/labs.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -298,16 +328,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/language-services.png" alt="Language Services Icon">
|
||||
<img src="generated/images/marketing/concept-icons/language-services.png" alt="Icono de Language Services">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">LANGUAGE SERVICES</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Language Services Icon (png) - <a href="generated/images/marketing/concept-icons/language-services.png" download>Download</a></span>
|
||||
<span>Icono de Language Services (png) - <a
|
||||
href="generated/images/marketing/concept-icons/language-services.png" download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Language Services Icon (svg) - <a href="generated/images/marketing/concept-icons/language-services.svg" download>Download</a></span>
|
||||
<span>Icono de Language Services (svg) - <a
|
||||
href="generated/images/marketing/concept-icons/language-services.svg" download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -317,16 +349,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/material.png" alt="Material Icon">
|
||||
<img src="generated/images/marketing/concept-icons/material.png" alt="Icono de Material">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">MATERIAL</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Material Icon (png) - <a href="generated/images/marketing/concept-icons/material.png" download>Download</a></span>
|
||||
<span>Icono de material (png) - <a href="generated/images/marketing/concept-icons/material.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Material Icon (svg) - <a href="generated/images/marketing/concept-icons/material.svg" download>Download</a></span>
|
||||
<span>Icono de material (svg) - <a href="generated/images/marketing/concept-icons/material.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -336,16 +370,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/protractor.png" alt="Protractor Icon">
|
||||
<img src="generated/images/marketing/concept-icons/protractor.png" alt="Icono de Protractor">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">PROTRACTOR</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Protractor Icon (png) - <a href="generated/images/marketing/concept-icons/protractor.png" download>Download</a></span>
|
||||
<span>Icono de Protractor (png) - <a href="generated/images/marketing/concept-icons/protractor.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Protractor Icon (svg) - <a href="generated/images/marketing/concept-icons/protractor.svg" download>Download</a></span>
|
||||
<span>Icono de Protractor (svg) - <a href="generated/images/marketing/concept-icons/protractor.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -355,16 +391,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/pwa.png" alt="PWA Icon">
|
||||
<img src="generated/images/marketing/concept-icons/pwa.png" alt="Icono de PWA">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">PWA</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>PWA Icon (png) - <a href="generated/images/marketing/concept-icons/pwa.png" download>Download</a></span>
|
||||
<span>Icono de PWA (png) - <a href="generated/images/marketing/concept-icons/pwa.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>PWA Icon (svg) - <a href="generated/images/marketing/concept-icons/pwa.svg" download>Download</a></span>
|
||||
<span>Icono de PWA (svg) - <a href="generated/images/marketing/concept-icons/pwa.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -374,16 +412,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/router.png" alt="Router Icon">
|
||||
<img src="generated/images/marketing/concept-icons/router.png" alt="Icono de Router">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">ROUTER</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Router Icon (png) - <a href="generated/images/marketing/concept-icons/router.png" download>Download</a></span>
|
||||
<span>Icono de Router (png) - <a href="generated/images/marketing/concept-icons/router.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Router Icon (svg) - <a href="generated/images/marketing/concept-icons/router.svg" download>Download</a></span>
|
||||
<span>Icono de Router (svg) - <a href="generated/images/marketing/concept-icons/router.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -393,16 +433,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/universal.png" alt="Universal Icon">
|
||||
<img src="generated/images/marketing/concept-icons/universal.png" alt="Icono Universal">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">UNIVERSAL</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Universal Icon (png) - <a href="generated/images/marketing/concept-icons/universal.png" download>Download</a></span>
|
||||
<span>Icono Universal (png) - <a href="generated/images/marketing/concept-icons/universal.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Universal Icon (svg) - <a href="generated/images/marketing/concept-icons/universal.svg" download>Download</a></span>
|
||||
<span>Icono Universal (svg) - <a href="generated/images/marketing/concept-icons/universal.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -412,7 +454,7 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div>
|
||||
<h2>CONCEPT & FEATURE ICONS</h2>
|
||||
<h2>ICONOS DE CONCEPTO Y CARACTERÍSTICAS</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -420,16 +462,19 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/dependency-injection.png" alt="Dependency Injection Icon">
|
||||
<img src="generated/images/marketing/concept-icons/dependency-injection.png"
|
||||
alt="Icono de inyección de dependencia">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">DEPENDENCY INJECTION</h3>
|
||||
<h3 class="l-space-left-3">INYECCIÓN DE DEPENDENCIA</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Dependency Injection Icon (png) - <a href="generated/images/marketing/concept-icons/dependency-injection.png" download>Download</a></span>
|
||||
<span>Icono de inyección de dependencia (png) - <a
|
||||
href="generated/images/marketing/concept-icons/dependency-injection.png" download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Dependency Injection Icon (svg) - <a href="generated/images/marketing/concept-icons/dependency-injection.svg" download>Download</a></span>
|
||||
<span>Icono de inyección de dependencia (svg) - <a
|
||||
href="generated/images/marketing/concept-icons/dependency-injection.svg" download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -439,16 +484,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/lazy-loading.png" alt="Lazy Loading Icon">
|
||||
<img src="generated/images/marketing/concept-icons/lazy-loading.png" alt="Icono de carga diferida">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">LAZY LOADING</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Lazy Loading Icon (png) - <a href="generated/images/marketing/concept-icons/lazy-loading.png" download>Download</a></span>
|
||||
<span>Icono de carga diferida (png) - <a href="generated/images/marketing/concept-icons/lazy-loading.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Lazy Loading Icon (svg) - <a href="generated/images/marketing/concept-icons/lazy-loading.svg" download>Download</a></span>
|
||||
<span>Icono de carga diferida (svg) - <a href="generated/images/marketing/concept-icons/lazy-loading.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -458,16 +505,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/libraries.png" alt="Libraries Icon">
|
||||
<img src="generated/images/marketing/concept-icons/libraries.png" alt="Icono de bibliotecas">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">LIBRARIES</h3>
|
||||
<h3 class="l-space-left-3">Librerías</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Libraries Icon (png) - <a href="generated/images/marketing/concept-icons/libraries.png" download>Download</a></span>
|
||||
<span>Icono de bibliotecas (png) - <a href="generated/images/marketing/concept-icons/libraries.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Libraries Icon (svg) - <a href="generated/images/marketing/concept-icons/libraries.svg" download>Download</a></span>
|
||||
<span>Icono de librerías (svg) - <a href="generated/images/marketing/concept-icons/libraries.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -477,16 +526,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/performance.png" alt="Performance Icon">
|
||||
<img src="generated/images/marketing/concept-icons/performance.png" alt="Icono de rendimiento">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">PERFORMANCE</h3>
|
||||
<h3 class="l-space-left-3">RENDIMIENTO</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Performance Icon (png) - <a href="generated/images/marketing/concept-icons/performance.png" download>Download</a></span>
|
||||
<span>Icono de rendimiento (png) - <a href="generated/images/marketing/concept-icons/performance.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Performance Icon (svg) - <a href="generated/images/marketing/concept-icons/performance.svg" download>Download</a></span>
|
||||
<span>Icono de rendimiento (svg) - <a href="generated/images/marketing/concept-icons/performance.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -496,16 +547,18 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="presskit-image-container">
|
||||
<img src="generated/images/marketing/concept-icons/templates.png" alt="Templates Icon">
|
||||
<img src="generated/images/marketing/concept-icons/templates.png" alt="Icono de plantillas">
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="l-space-left-3">TEMPLATES</h3>
|
||||
<h3 class="l-space-left-3">PLANTILLAS</h3>
|
||||
<ul class="l-space-left-3">
|
||||
<li>
|
||||
<span>Templates Icon (png) - <a href="generated/images/marketing/concept-icons/templates.png" download>Download</a></span>
|
||||
<span>Icono de plantillas (png) - <a href="generated/images/marketing/concept-icons/templates.png"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Templates Icon (svg) - <a href="generated/images/marketing/concept-icons/templates.svg" download>Download</a></span>
|
||||
<span>Icono de plantillas (svg) - <a href="generated/images/marketing/concept-icons/templates.svg"
|
||||
download>Descargar</a></span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@ -515,98 +568,113 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div>
|
||||
<h2>PRESS AND MEDIA</h2>
|
||||
<p>For inquiries regarding press and media please contact us at
|
||||
<a href="mailto:press@angular.io">press@angular.io</a>.</p>
|
||||
<h2>PRENSA Y MEDIOS </h2>
|
||||
<p> Para consultas sobre prensa y medios, contáctenos en
|
||||
<a href="mailto:press@angular.io">press@angular.io</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
div.bullets ul {
|
||||
list-style-type: disc !important; margin-left: 1em !important;
|
||||
list-style-type: disc !important;
|
||||
margin-left: 1em !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="bullets">
|
||||
<h2>BRAND NAMES</h2>
|
||||
<h3>Angular</h3>
|
||||
<p>The name <b>Angular</b> represents the work and promises provided to you by the Angular team.</p>
|
||||
<h2>NOMBRES DE MARCAS</h2>
|
||||
<h3>Angular</h3>
|
||||
<p>El Nombre <b>Angular</b> representa el trabajo y las promesas que le proporcionó el equipo de Angular.</p>
|
||||
|
||||
<p>When not specified, Angular is assumed to be referring to the latest and greatest stable version from the Angular Team.</p>
|
||||
<p> Cuando no se especifica, se supone que Angular se refiere a la última y mejor versión estable del equipo de
|
||||
Angular. </p>
|
||||
<h4>Ejemplo</h4>
|
||||
<p><b> Versión v4.1 ya disponible </b>: Nos complace anunciar que la última versión de Angular ya está
|
||||
disponible. ¡Mantenerse actualizado es fácil! </p>
|
||||
|
||||
<h4>Example</h4>
|
||||
<p><b>Version v4.1 now available</b> - We are pleased to announce that the latest release of Angular is now available. Staying up to date is easy!</p>
|
||||
<h4>Ejemplo</h4>
|
||||
|
||||
<h4>Example</h4>
|
||||
<p><b>Correcto: </b> "Nuevo <code>*ngIf</code> capacidades</b>—nuevo en la versión 4.0 es la capacidad de
|
||||
..."</p>
|
||||
<p><b style="color: red">Incorrecto: </b> "Nuevo <code>*ngIf</code> capacidades en Angular 4</b>—Angular 4
|
||||
introduce la capacidad de ..."</p>
|
||||
|
||||
<p><b>Correct: </b> "New <code>*ngIf</code> capabilities</b>—new in version 4.0 is the ability to ..."</p>
|
||||
<p><b style="color: red">Incorrect: </b> "New <code>*ngIf</code> capabilities in Angular 4</b>—Angular 4 introduces the ability to ..."</p>
|
||||
<p><b>Razonamiento</b></p>
|
||||
|
||||
<p><b>Reasoning</b></p>
|
||||
<p> Al no usar "Angular 4" en el título, el contenido aún se siente aplicable y útil después de que se hayan
|
||||
lanzado las versiones 5, 6, 7, ya que es poco probable que la sintaxis cambie a corto y mediano plazo. </p>
|
||||
|
||||
<p>By not using “Angular 4” in the title, the content still feels applicable and useful after version 5, 6, 7 have been released, as the syntax is unlikely to change in the short and medium term.</p>
|
||||
<h3>AngularJS</h3>
|
||||
|
||||
<h3>AngularJS</h3>
|
||||
<p><b> AngularJS </b> es la serie v1.x de trabajo y promesas proporcionadas por el equipo de Angular. </p>
|
||||
|
||||
<p><b>AngularJS</b> is the v1.x series of work and promises provided by the Angular team.</p>
|
||||
<h4>Ejemplos</h4>
|
||||
<ol>
|
||||
<li> AngularJS es uno de los frameworks más utilizados en la web en la actualidad (por número de proyectos). </li>
|
||||
<li> Millones de desarrolladores están construyendo actualmente con AngularJS. </li>
|
||||
<li> Los desarrolladores están comenzando a actualizar de AngularJS a Angular. </li>
|
||||
<li> Estoy actualizando mi aplicación de AngularJS a Angular. </li>
|
||||
<li> Estoy usando AngularJS Material en este proyecto. </li>
|
||||
</ol>
|
||||
|
||||
<h4>Examples</h4>
|
||||
<ol>
|
||||
<li>AngularJS is one of the most used framework on the web today (by number of projects).</li>
|
||||
<li>Millions of developers are currently building with AngularJS.</li>
|
||||
<li>Developers are beginning to upgrade from AngularJS to Angular.</li>
|
||||
<li>I’m upgrading my application from AngularJS to Angular.</li>
|
||||
<li>I'm using AngularJS Material on this project.</li>
|
||||
</ol>
|
||||
|
||||
<p>AngularJS projects should use the
|
||||
<p>Los proyectos de AngularJS deben usar el
|
||||
<a href="assets/images/logos/angularjs/AngularJS-Shield.svg" title="AngularJS logo">
|
||||
original AngularJS logo</a> / icon, and not the Angular icon.</p>
|
||||
logo original de AngularJS </a> / icono, y no el icono de Angular.</p>
|
||||
|
||||
<img src="assets/images/logos/angularjs/AngularJS-Shield.svg" alt="AngularJS Logo" style="margin-left:20px;" height="128" width="128">
|
||||
<img src="assets/images/logos/angularjs/AngularJS-Shield.svg" alt="AngularJS Logo" style="margin-left:20px;"
|
||||
height="128" width="128">
|
||||
|
||||
<h3>Angular Material</h3>
|
||||
<h3>Angular Material</h3>
|
||||
|
||||
<p>This is the work being performed by the Angular team to provide Material Design components for Angular applications.</p>
|
||||
<p>Este es el trabajo que está realizando el equipo de Angular para proporcionar componentes de Material Design
|
||||
para aplicaciones Angular.</p>
|
||||
|
||||
<h3>AngularJS Material</h3>
|
||||
<h3>Material de AngularJS</h3>
|
||||
|
||||
<p>This is the work being performed by the Angular team on Material Design components that are compatible with AngularJS.</p>
|
||||
<p>Este es el trabajo que está realizando el equipo de Angular en los componentes de Material Design que son
|
||||
compatibles con AngularJS.</p>
|
||||
|
||||
<h3>3rd Party Projects</h3>
|
||||
<h3>Proyectos de terceros</h3>
|
||||
|
||||
<p><b>X for Angular</b></p>
|
||||
<p><b>X para Angular</b></p>
|
||||
|
||||
<p>3rd parties should use the terminology “X for Angular” or “ng-X” for software projects. Projects should avoid the use of Angular X (e.g. Angular UI Toolkit), as it could create authorship confusion. This rule does not apply to events or meetup groups.</p>
|
||||
<p>Los terceros deben utilizar la terminología "X para Angular" o "ng-X" para proyectos de software. Los
|
||||
proyectos deben evitar el uso de Angular X (por ejemplo, Angular UI Toolkit), ya que podría crear confusión en
|
||||
la autoría. Esta regla no se aplica a eventos o grupos de reuniones.</p>
|
||||
|
||||
<p>Developers should avoid using Angular version numbers in project names, as this will artificially limit their projects by tying them to a point in time of Angular, or will require renaming over time.</p>
|
||||
<p>Los desarrolladores deben evitar el uso de números de versión de Angular en los nombres de los proyectos, ya
|
||||
que esto limitará artificialmente sus proyectos al vincularlos a un punto en el tiempo de Angular, o requerirá
|
||||
un cambio de nombre con el tiempo.</p>
|
||||
|
||||
<p>Where a codename or shortname is used, such as on npm or github, some are acceptable, some are not acceptable.</p>
|
||||
<p>Cuando se usa un nombre en clave o un nombre abreviado, como en npm o github, algunos son aceptables, otros
|
||||
no.</p>
|
||||
|
||||
<b>Do not use</b>
|
||||
<ul>
|
||||
<li><code>ng2-</code></li>
|
||||
<li><code>angular2-</code></li>
|
||||
</ul>
|
||||
<b>No utilices</b>
|
||||
<ul>
|
||||
<li><code>ng2-</code></li>
|
||||
<li><code>angular2-</code></li>
|
||||
</ul>
|
||||
|
||||
<b>OK to use</b>
|
||||
<ul>
|
||||
<li><code>ng-</code></li>
|
||||
<li><code>angular-</code></li>
|
||||
</ul>
|
||||
<b>Utiliza</b>
|
||||
<ul>
|
||||
<li><code>ng-</code></li>
|
||||
<li><code>angular-</code></li>
|
||||
</ul>
|
||||
|
||||
<p>As always, component and directive selectors should not begin with “ng-” selectors as this will conflict with components and directives provided by the Angular team.</p>
|
||||
<p>Como siempre, los selectores de componentes y directivas no deben comenzar con selectores "ng-", ya que esto
|
||||
entrará en conflicto con los componentes y las directivas proporcionadas por el equipo de Angular.</p>
|
||||
|
||||
<h4>Examples</h4>
|
||||
<ul>
|
||||
<li>The ng-BE team just launched <code>ng-health</code> to help developers track their own health.</li>
|
||||
<li>I’m going to use NativeScript for Angular to take advantage of native UI widgets.</li>
|
||||
<li><code>ReallyCoolTool</code> for Angular.</li>
|
||||
<li><code>ReallyCoolTool</code> for AngularJS.</li>
|
||||
</ul>
|
||||
<h4>Ejemplos</h4>
|
||||
<ul>
|
||||
<li>El equipo ng-BE acaba de lanzar <code>ng-health</code> Para ayudar a los desarrolladores a rastrear su
|
||||
propia salud.</li>
|
||||
<li>Voy a usar NativeScript para Angular para aprovechar los widgets de IU nativos.</li>
|
||||
<li><code>ReallyCoolTool</code> para Angular.</li>
|
||||
<li><code>ReallyCoolTool</code> para AngularJS.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -614,10 +682,10 @@
|
||||
<div class="presskit-row">
|
||||
<div class="presskit-inner">
|
||||
<div class="bullets">
|
||||
<h2>TERMS WE USE</h2>
|
||||
<h2>TÉRMINOS QUE UTILIZAMOS</h2>
|
||||
<p>
|
||||
We often use terms that are not part of our brand,
|
||||
but we want to remain consistent on the styling and use of them to prevent confusion and to appear unified.
|
||||
A menudo utilizamos términos que no forman parte de nuestra marca,
|
||||
pero queremos ser consistentes en el estilo y el uso de ellos para evitar confusiones y parecer unificados.
|
||||
</p>
|
||||
<ul>
|
||||
<li>Ahead of Time compilation (AOT)</li>
|
||||
|
@ -1,13 +1,13 @@
|
||||
# Contributing to resources.json
|
||||
# Contribuir a resources.json
|
||||
|
||||
## About this list
|
||||
We maintain a small list of some of the top Angular resources from across the community, stored in `resources.json`. This list is not intended to be comprehensive, but to act as a starting point to connect Angular developers to the rest of the community.
|
||||
## Acerca de esta lista
|
||||
Mantenemos una pequeña lista de algunos de los principales recursos de Angular de toda la comunidad, almacenados en `resources.json`. Esta lista no pretende ser completa, sino actuar como un punto de partida para conectar a los desarrolladores de Angular con el resto de la comunidad.
|
||||
|
||||
## How do I get listed?
|
||||
While we can't accept all contributions, qualifying contributions can be submitted via a PR adding yourself to the `resources.json` file. All contributions should be in the appropriate section and must meet the following criteria:
|
||||
## ¿Cómo me incluyo?
|
||||
Si bien no podemos aceptar todas las contribuciones, las contribuciones que califiquen se pueden enviar a través de un PR que se agregue al archivo `resources.json`. Todas las contribuciones deben estar en la sección correspondiente y deben cumplir con los siguientes criterios:
|
||||
|
||||
1. Your contribution must be valid, and contain a link to a page talking specifically about using Angular
|
||||
1. Your contribution should have a clear and concise title and description
|
||||
1. Your resource should follow our brand guidelines (see our [Presskit](presskit))
|
||||
1. Your resource should have significant benefit to Angular developers
|
||||
1. Your resource should already have traction and praise from Angular developers
|
||||
1. Su contribución debe ser válida y contener un enlace a una página que hable específicamente sobre el uso de Angular
|
||||
1. Tu contribución debe tener un título y una descripción claros y concisos.
|
||||
1. Su recurso debe seguir nuestras pautas de marca (consulte nuestro [Presskit](presskit))
|
||||
1. Su recurso debería tener un beneficio significativo para los desarrolladores de Angular
|
||||
1. Su recurso ya debería tener tracción y elogios de los desarrolladores de Angular
|
@ -1,5 +1,5 @@
|
||||
<header class="marketing-banner">
|
||||
<h1 class="banner-headline no-toc no-anchor">Explore Angular Resources</h1>
|
||||
<h1 class="banner-headline no-toc no-anchor">Explore Recursos de Angular</h1>
|
||||
</header>
|
||||
|
||||
<article>
|
||||
|
@ -1,37 +1,37 @@
|
||||
{
|
||||
"Community": {
|
||||
"Comunidad": {
|
||||
"order": 3,
|
||||
"subCategories": {
|
||||
"Community Curations": {
|
||||
"Elecciones de la comunidad": {
|
||||
"order": 1,
|
||||
"resources": {
|
||||
"awesome-angular-components": {
|
||||
"desc": "A community index of components and libraries maintained on GitHub",
|
||||
"title": "Catalog of Angular Components & Libraries",
|
||||
"desc": "Un índice de componentes y librerías de la comunidad mantenido en GitHub",
|
||||
"title": "Catálogo de librerías y componentes Angular",
|
||||
"url": "https://github.com/brillout/awesome-angular-components"
|
||||
},
|
||||
"angular-ru": {
|
||||
"desc": "Angular-RU Community on GitHub is a single entry point for all resources, chats, podcasts and meetups for Angular in Russia.",
|
||||
"desc": "La comunidad Angular-RU en GitHub es un punto de entrada único para todos los recursos, chats, podcasts y reuniones de Angular en Rusia.",
|
||||
"title": "Angular Conferences and Angular Camps in Moscow, Russia.",
|
||||
"url": "https://angular-ru.github.io/"
|
||||
},
|
||||
"made-with-angular": {
|
||||
"desc": "A showcase of web apps built with Angular.",
|
||||
"title": "Made with Angular",
|
||||
"desc": "Una muestra de aplicaciones web creadas con Angular.",
|
||||
"title": "Hecho con Angular",
|
||||
"url": "https://www.madewithangular.com/"
|
||||
},
|
||||
"angular-subreddit": {
|
||||
"desc": "An Angular-dedicated subreddit.",
|
||||
"desc": "Un subreddit dedicado a Angular.",
|
||||
"title": "Angular Subreddit",
|
||||
"url": "https://www.reddit.com/r/Angular2/"
|
||||
},
|
||||
"angular-devto": {
|
||||
"desc": "Read and share content and chat about Angular on DEV Community.",
|
||||
"desc": "Lee, comparte contenido y chatea sobre Angular en la comunidad DEV.",
|
||||
"url": "https://dev.to/t/angular",
|
||||
"title": "DEV Community"
|
||||
},
|
||||
"angular-in-depth": {
|
||||
"desc": "The place where advanced Angular concepts are explained",
|
||||
"desc": "El lugar donde se explican los conceptos de Angular avanzados",
|
||||
"url": "https://blog.angularindepth.com",
|
||||
"title": "Angular In Depth"
|
||||
}
|
||||
@ -41,25 +41,25 @@
|
||||
"order": 3,
|
||||
"resources": {
|
||||
"sdfjkdkfj": {
|
||||
"desc": "Adventures in Angular is a weekly podcast dedicated to the Angular platform and related technologies, tools, languages, and practices.",
|
||||
"desc": "Adventures in Angular es un podcast semanal dedicado a la plataforma Angular y tecnologías relacionadas, herramientas, lenguajes y prácticas.",
|
||||
"logo": "",
|
||||
"title": "Adventures in Angular",
|
||||
"url": "https://devchat.tv/adv-in-angular/"
|
||||
},
|
||||
"sdlkfjsldfkj": {
|
||||
"desc": "Weekly video podcast hosted by Jeff Whelpley with all the latest and greatest happenings in the wild world of Angular.",
|
||||
"desc": "Podcast de video semanal presentado por Jeff Whelpley con los últimos y más grandes acontecimientos en el salvaje mundo de Angular.",
|
||||
"logo": "",
|
||||
"title": "AngularAir",
|
||||
"url": "https://angularair.com/"
|
||||
},
|
||||
"sdlkfjsldfkz": {
|
||||
"desc": "A weekly German podcast for Angular on the go",
|
||||
"desc": "Un podcast alemán semanal para Angular muy activo.",
|
||||
"logo": "",
|
||||
"title": "Happy Angular Podcast",
|
||||
"title": "Podcast de Happy Angular",
|
||||
"url": "https://happy-angular.de/"
|
||||
},
|
||||
"ngruair": {
|
||||
"desc": "Russian language video podcast about Angular.",
|
||||
"desc": "Podcast de video en ruso sobre Angular.",
|
||||
"logo": "",
|
||||
"title": "NgRuAir",
|
||||
"url": "https://github.com/ngRuAir/ngruair"
|
||||
@ -68,80 +68,75 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Development": {
|
||||
"Desarrollo": {
|
||||
"order": 1,
|
||||
"subCategories": {
|
||||
"Cross-Platform Development": {
|
||||
"Desarrollo multiplataforma": {
|
||||
"order": 5,
|
||||
"resources": {
|
||||
"a3b": {
|
||||
"desc": "Ionic offers a library of mobile-optimized HTML, CSS and JS components and tools for building highly interactive native and progressive web apps.",
|
||||
"desc": "Ionic ofrece una biblioteca de componentes y herramientas HTML, CSS y JS optimizados para dispositivos móviles para crear aplicaciones web nativas y progresivas altamente interactivas.",
|
||||
"logo": "http://ionicframework.com/img/ionic-logo-white.svg",
|
||||
"title": "Ionic",
|
||||
"url": "https://ionicframework.com/docs"
|
||||
},
|
||||
"a4b": {
|
||||
"desc": "Electron Platform for Angular.",
|
||||
"desc": "Plataforma de Electron para Angular.",
|
||||
"logo": "",
|
||||
"title": "Electron",
|
||||
"url": "https://github.com/maximegris/angular-electron"
|
||||
},
|
||||
"ab": {
|
||||
"desc": "NativeScript is how you build cross-platform, native iOS and Android apps with Angular and TypeScript. Get 100% access to native APIs via JavaScript and reuse of packages from NPM, CocoaPods and Gradle. Open source and backed by Telerik.",
|
||||
"desc": "NativeScript es la forma de crear aplicaciones nativas de iOS y Android multiplataforma con Angular y TypeScript. Obtenga acceso al 100% a las API nativas a través de JavaScript y reutilice paquetes de NPM, CocoaPods y Gradle. Código abierto y respaldado por Telerik.",
|
||||
"logo": "",
|
||||
"title": "NativeScript",
|
||||
"url": "https://docs.nativescript.org/angular/start/introduction"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Data Libraries": {
|
||||
"Librerías de datos": {
|
||||
"order": 3,
|
||||
"resources": {
|
||||
"formly": {
|
||||
"desc": "Formly is a dynamic (JSON powered) form library, built on top of Angular Reactive Forms.",
|
||||
"title": "Formly",
|
||||
"url": "https://formly.dev"
|
||||
},
|
||||
"rx-web": {
|
||||
"desc": "RxWeb Reactive Form Validators provides all types of complex, conditional, cross field, and dynamic validation on validator-based reactive forms, model-based reactive forms, and template driven forms.",
|
||||
"title": "RxWeb Reactive Form Validators",
|
||||
"desc": "RxWeb Reactive Form Validators proporciona todo tipo de validación compleja, condicional, de campo cruzado y dinámica en formularios reactivos basados en validadores, formularios reactivos basados en modelos y formularios controlados por plantillas.",
|
||||
"title": "Validadores de formularios reactivos RxWeb",
|
||||
"url": "https://www.rxweb.io"
|
||||
},
|
||||
"-KLIzHDRfiB3d7W7vk-e": {
|
||||
"desc": "Reactive Extensions for Angular",
|
||||
"desc": "Extensiones reactivas para Angular",
|
||||
"title": "ngrx",
|
||||
"url": "https://ngrx.io/"
|
||||
},
|
||||
"ngxs": {
|
||||
"desc": "NGXS is a state management pattern + library for Angular. NGXS is modeled after the CQRS pattern popularly implemented in libraries like Redux and NgRx but reduces boilerplate by using modern TypeScript features such as classes and decorators.",
|
||||
"desc": "NGXS es un patrón de gestión de estado + librería para Angular. NGXS se basa en el patrón CRS implementado popularmente en librerías como Redux y NgRx, pero reduce el texto estándar mediante el uso de características modernas de TypeScript, como clases y decoradores.",
|
||||
"title": "NGXS",
|
||||
"url": "https://ngxs.io/"
|
||||
},
|
||||
"akita": {
|
||||
"desc": "Akita is a state management pattern, built on top of RxJS, which takes the idea of multiple data stores from Flux and the immutable updates from Redux, along with the concept of streaming data, to create the Observable Data Store model.",
|
||||
"desc": "Akita es un patrón de administración de estado, construido sobre RxJS, que toma la idea de múltiples almacenes de datos de Flux y las actualizaciones inmutables de Redux, junto con el concepto de transmisión de datos, para crear el modelo Observable Data Store.",
|
||||
"title": "Akita",
|
||||
"url": "https://netbasal.gitbook.io/akita/"
|
||||
},
|
||||
"ab": {
|
||||
"desc": "The official library for Firebase and Angular",
|
||||
"desc": "La biblioteca oficial de Firebase y Angular",
|
||||
"logo": "",
|
||||
"title": "Angular Fire",
|
||||
"url": "https://github.com/angular/angularfire2"
|
||||
"url": "https://github.com/angular/angularfire"
|
||||
},
|
||||
"ab2": {
|
||||
"desc": "Use Angular and Meteor to build full-stack JavaScript apps for Mobile and Desktop.",
|
||||
"desc": "Utilice Angular y Meteor para crear aplicaciones JavaScript de pila completa para dispositivos móviles y de escritorio.",
|
||||
"logo": "http://www.angular-meteor.com/images/logo.png",
|
||||
"title": "Meteor",
|
||||
"url": "https://github.com/urigo/angular-meteor"
|
||||
},
|
||||
"ab3": {
|
||||
"desc": "Apollo is a data stack for modern apps, built with GraphQL.",
|
||||
"desc": "Apollo es una pila de datos para aplicaciones modernas, construida con GraphQL.",
|
||||
"logo": "http://docs.apollostack.com/logo/large.png",
|
||||
"title": "Apollo",
|
||||
"url": "https://www.apollographql.com/docs/angular/"
|
||||
},
|
||||
"ngx-api-utils": {
|
||||
"desc": "ngx-api-utils is a lean library of utilities and helpers to quickly integrate any HTTP API (REST, Ajax, and any other) with Angular.",
|
||||
"desc": "ngx-api-utils es una biblioteca ajustada de utilidades y ayudantes para integrar rápidamente cualquier API HTTP (REST, Ajax y cualquier otra) con Angular.",
|
||||
"logo": "",
|
||||
"title": "ngx-api-utils",
|
||||
"url": "https://github.com/ngx-api-utils/ngx-api-utils"
|
||||
@ -152,281 +147,274 @@
|
||||
"order": 1,
|
||||
"resources": {
|
||||
"ab": {
|
||||
"desc": "VS Code is a Free, Lightweight Tool for Editing and Debugging Web Apps.",
|
||||
"desc": "VS Code es una herramienta ligera y gratuita para editar y depurar aplicaciones web.",
|
||||
"logo": "",
|
||||
"title": "Visual Studio Code",
|
||||
"url": "http://code.visualstudio.com/"
|
||||
},
|
||||
"ab2": {
|
||||
"desc": "Lightweight yet powerful IDE, perfectly equipped for complex client-side development and server-side development with Node.js",
|
||||
"desc": "IDE ligero pero potente, perfectamente equipado para el desarrollo complejo del lado del cliente y el desarrollo del lado del servidor con Node.js",
|
||||
"logo": "",
|
||||
"title": "WebStorm",
|
||||
"url": "https://www.jetbrains.com/webstorm/"
|
||||
},
|
||||
"ab3": {
|
||||
"desc": "Capable and Ergonomic Java * IDE",
|
||||
"desc": "Java capaz y ergonómico * IDE",
|
||||
"logo": "",
|
||||
"title": "IntelliJ IDEA",
|
||||
"url": "https://www.jetbrains.com/idea/"
|
||||
},
|
||||
"angular-ide": {
|
||||
"desc": "Built first and foremost for Angular. Turnkey setup for beginners; powerful for experts.",
|
||||
"desc": "Construido ante todo para Angular. Configuración llave en mano para principiantes; poderoso para expertos.",
|
||||
"title": "Angular IDE by Webclipse",
|
||||
"url": "https://www.genuitec.com/products/angular-ide"
|
||||
},
|
||||
"amexio-canvas": {
|
||||
"desc": "Amexio Canvas is Drag and Drop Environment to create Fully Responsive Web and Smart Device HTML5/Angular Apps. Code will be auto generated and hot deployed by the Canvas for live testing. Out of the box 50+ Material Design Theme support. Commit your code to GitHub public or private repository.",
|
||||
"desc": "Amexio Canvas es un entorno de arrastrar y soltar para crear aplicaciones web y de dispositivos inteligentes HTML5 / Angular totalmente sensibles El código se generará automáticamente y se implementará en caliente mediante Canvas para realizar pruebas en vivo. Soporte listo para usar 50+ Temas de Diseño Material. Confirme su código en el repositorio público o privado de GitHub.",
|
||||
"title": "Amexio Canvas Web Based Drag and Drop IDE by MetaMagic",
|
||||
"url": "https://amexio.tech/"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Tooling": {
|
||||
"Montaje": {
|
||||
"order": 2,
|
||||
"resources": {
|
||||
"a1": {
|
||||
"desc": "A Google Chrome Dev Tools extension for debugging Angular applications.",
|
||||
"desc": "Una extensión de Google Chrome Dev Tools para depurar aplicaciones angular.",
|
||||
"logo": "https://augury.angular.io/images/augury-logo.svg",
|
||||
"title": "Augury",
|
||||
"url": "http://augury.angular.io/"
|
||||
},
|
||||
"b1": {
|
||||
"desc": "Server-side Rendering for Angular apps.",
|
||||
"desc": "Representación del lado del servidor para aplicaciones Angular.",
|
||||
"logo": "https://cloud.githubusercontent.com/assets/1016365/10639063/138338bc-7806-11e5-8057-d34c75f3cafc.png",
|
||||
"title": "Angular Universal",
|
||||
"url": "https://angular.io/guide/universal"
|
||||
},
|
||||
"c1": {
|
||||
"desc": "Lightweight development only Node.js® server",
|
||||
"desc": "Servidor Node.js® de desarrollo ligero",
|
||||
"logo": "",
|
||||
"title": "Lite-server",
|
||||
"url": "https://github.com/johnpapa/lite-server"
|
||||
},
|
||||
"cli": {
|
||||
"desc": "The official Angular CLI makes it easy to create and develop applications from initial commit to production deployment. It already follows our best practices right out of the box!",
|
||||
"desc": "La CLI oficial de Angular facilita la creación y el desarrollo de aplicaciones desde el compromiso inicial hasta la implementación de producción. ¡Ya sigue nuestras mejores prácticas desde el primer momento!",
|
||||
"title": "Angular CLI",
|
||||
"url": "https://cli.angular.io"
|
||||
},
|
||||
"d1": {
|
||||
"desc": "Static analysis for Angular projects.",
|
||||
"desc": "Análisis estático para proyectos Angular.",
|
||||
"logo": "",
|
||||
"title": "Codelyzer",
|
||||
"url": "https://github.com/mgechev/codelyzer"
|
||||
},
|
||||
"f1": {
|
||||
"desc": "This tool generates dedicated documentation for Angular applications.",
|
||||
"desc": "Esta herramienta genera documentación dedicada para aplicaciones Angular.",
|
||||
"logo": "",
|
||||
"title": "Compodoc",
|
||||
"url": "https://github.com/compodoc/compodoc"
|
||||
},
|
||||
"angular-playground": {
|
||||
"desc": "UI development environment for building, testing, and documenting Angular applications.",
|
||||
"title": "Angular Playground",
|
||||
"desc": "Entorno de desarrollo de la interfaz de usuario para crear, probar y documentar aplicaciones Angular.",
|
||||
"title": "Patio de juegos Angular",
|
||||
"url": "http://www.angularplayground.it/"
|
||||
},
|
||||
"nx": {
|
||||
"desc": "Nx (Nrwl Extensions for Angular) is an open source toolkit built on top of Angular CLI to help enterprise teams develop Angular at scale.",
|
||||
"desc": "Nx (Nrwl Extensions for Angular) es un kit de herramientas de código abierto construido sobre Angular CLI para ayudar a los equipos empresariales a desarrollar Angular a escala.",
|
||||
"title": "Nx",
|
||||
"logo": "https://nrwl.io/assets/nx-logo.png",
|
||||
"url": "https://nrwl.io/nx"
|
||||
},
|
||||
"uijar": {
|
||||
"desc": "A drop in module to automatically create a living style guide based on the test you write for your components.",
|
||||
"desc": "Un módulo desplegable para crear automáticamente una guía de estilo viva basada en la prueba que escribe para sus componentes.",
|
||||
"logo": "",
|
||||
"title": "UI-jar - Test Driven Style Guide Development",
|
||||
"title": "UI-jar: desarrollo de guías de estilo basado en pruebas",
|
||||
"url": "https://github.com/ui-jar/ui-jar"
|
||||
},
|
||||
"protactor": {
|
||||
"desc": "The official end to end testing framework for Angular apps",
|
||||
"desc": "El marco oficial de prueba de extremo a extremo para aplicaciones Angular",
|
||||
"logo": "",
|
||||
"title": "Protractor",
|
||||
"url": "https://protractor.angular.io/"
|
||||
},
|
||||
"scully": {
|
||||
"desc": "Scully (Jamstack Toolchain for Angular) makes building, testing, and deploying Jamstack apps extremely simple.",
|
||||
"title": "Scully",
|
||||
"logo": "https://raw.githubusercontent.com/scullyio/scully/main/assets/logos/PNG/Green/scullyio-logo-green.png",
|
||||
"url": "https://scully.io"
|
||||
}
|
||||
}
|
||||
},
|
||||
"UI Components": {
|
||||
"Componentes UI": {
|
||||
"order": 4,
|
||||
"resources": {
|
||||
"AngularUIToolkit": {
|
||||
"desc": "Angular UI Toolkit: 115 professionally maintained UI components ranging from a robust grid to charts and more. Try for free & build Angular apps faster.",
|
||||
"title": "Angular UI Toolkit",
|
||||
"desc": "Kit de herramientas de interfaz de usuario angular: 115 componentes de interfaz de usuario mantenidos profesionalmente que van desde una cuadrícula robusta hasta gráficos y más. Pruébelo gratis y cree aplicaciones Angular más rápido.",
|
||||
"title": "Kit de herramientas Angular UI",
|
||||
"url": "https://www.angular-ui-tools.com"
|
||||
},
|
||||
"SenchaforAngular": {
|
||||
"desc": "Build modern web apps faster with 115+ pre-built UI components. Try for free and download today.",
|
||||
"title": "Sencha for Angular",
|
||||
"desc": "Cree aplicaciones web modernas más rápido con más de 115 UI Componentes prediseñados. Pruébelo gratis y descárguelo hoy.",
|
||||
"title": "Sencha para Angular",
|
||||
"url": "https://www.sencha.com/products/extangular/"
|
||||
},
|
||||
"IgniteUIforAngular": {
|
||||
"desc": "Ignite UI for Angular is a dependency-free Angular toolkit for building modern web apps.",
|
||||
"title": "Ignite UI for Angular",
|
||||
"desc": "Ignite UI para Angular es un kit de herramientas Angular sin dependencia para crear aplicaciones web modernas.",
|
||||
"title": "Ignite UI para Angular",
|
||||
"url": "https://www.infragistics.com/products/ignite-ui-angular?utm_source=angular.io&utm_medium=Referral&utm_campaign=Angular"
|
||||
},
|
||||
"DevExtreme": {
|
||||
"desc": "50+ UI components including data grid, pivot grid, scheduler, charts, editors, maps and other multi-purpose controls for creating highly responsive web applications for touch devices and traditional desktops.",
|
||||
"desc": "Más de 50 componentes UI que incluyen cuadrícula de datos, cuadrícula dinámica, programador, gráficos, editores, mapas y otros controles multipropósito para crear aplicaciones web altamente receptivas para dispositivos táctiles y escritorios tradicionales.",
|
||||
"title": "DevExtreme",
|
||||
"url": "https://js.devexpress.com/Overview/Angular/"
|
||||
},
|
||||
"234237": {
|
||||
"desc": "UX guidelines, HTML/CSS framework, and Angular components working together to craft exceptional experiences",
|
||||
"title": "Clarity Design System",
|
||||
"desc": "Las pautas de UX, el marco HTML / CSS y los componentes Angular trabajan juntos para crear experiencias excepcionales",
|
||||
"title": "Sistema de diseño de Clarity",
|
||||
"url": "https://vmware.github.io/clarity/"
|
||||
},
|
||||
"-KMVB8P4TDfht8c0L1AE": {
|
||||
"desc": "The Angular version of the Angular UI Bootstrap library. This library is being built from scratch in Typescript using the Bootstrap 4 CSS framework.",
|
||||
"desc": "La versión de Angular de la biblioteca Bootstrap de Angular UI. Esta biblioteca se está construyendo desde cero en Typescript utilizando el marco CSS Bootstrap 4.",
|
||||
"title": "ng-bootstrap",
|
||||
"url": "https://ng-bootstrap.github.io/"
|
||||
},
|
||||
"4ab": {
|
||||
"desc": "Native Angular components & directives for Lightning Design System",
|
||||
"desc": "Directivas y componentes Angular nativos para Lightning Design System",
|
||||
"logo": "http://ng-lightning.github.io/ng-lightning/img/shield.svg",
|
||||
"title": "ng-lightning",
|
||||
"url": "http://ng-lightning.github.io/ng-lightning/"
|
||||
},
|
||||
"7ab": {
|
||||
"desc": "UI components for hybrid mobile apps with bindings for both Angular & AngularJS.",
|
||||
"desc": "Componentes UI para aplicaciones móviles híbridas con enlaces para Angular y AngularJS.",
|
||||
"title": "Onsen UI",
|
||||
"url": "https://onsen.io/v2/"
|
||||
},
|
||||
"a2b": {
|
||||
"desc": "PrimeNG is a collection of rich UI components for Angular",
|
||||
"desc": "PrimeNG es una colección rica de componentes UI para Angular",
|
||||
"logo": "http://www.primefaces.org/primeng/showcase/resources/images/primeng.svg",
|
||||
"title": "Prime Faces",
|
||||
"url": "http://www.primefaces.org/primeng/"
|
||||
},
|
||||
"a3b": {
|
||||
"desc": "A professional grade library of Angular UI components written in TypeScript that includes our Data Grid, TreeView, Charts, Editors, DropDowns, DatePickers, and many more. Features include support for AOT compilation, Tree Shaking for high-performance, localization, and accessibility.",
|
||||
"desc": "Una biblioteca de grado profesional de los Componentes UI de Angular escrita en TypeScript que incluye nuestro Data Grid, TreeView, Charts, Editors, DropDowns, DatePickers y muchos más. Las características incluyen soporte para la compilación AOT, Tree Shaking para alto rendimiento, localización y accesibilidad.",
|
||||
"logo": "",
|
||||
"title": "Kendo UI",
|
||||
"url": "http://www.telerik.com/kendo-angular-ui/"
|
||||
},
|
||||
"a5b": {
|
||||
"desc": "High-performance UI controls with the most complete Angular support available. Wijmo’s controls are all written in TypeScript and have zero dependencies. FlexGrid control includes full declarative markup, including cell templates.",
|
||||
"desc": "Controles UI de Alto-Rendimiento con el soporte más completo para Angular. Wijmo’s controla todo lo que esta escrito en TypeScript y no tiene ninguna dependecia. El control FlexGrid incluye marcado declarativo completo, incluyendo plantillas de celda.",
|
||||
"logo": "http://wijmocdn.azureedge.net/wijmositeblob/wijmo-theme/logos/wijmo-55.png",
|
||||
"title": "Wijmo",
|
||||
"url": "http://wijmo.com/products/wijmo-5/"
|
||||
},
|
||||
"a6b": {
|
||||
"desc": "Material design inspired UI components for building great web apps. For mobile and desktop.",
|
||||
"desc": "El diseño de materiales inspiró la interfaz de usuario de Componentes para crear excelentes aplicaciones web. Para dispositivos móviles y de escritorio.",
|
||||
"logo": "",
|
||||
"title": "Vaadin",
|
||||
"url": "https://vaadin.com/elements"
|
||||
},
|
||||
"a7b": {
|
||||
"desc": "Native Angular directives for Bootstrap",
|
||||
"desc": "Directivas Angular nativas para Bootstrap",
|
||||
"logo": "",
|
||||
"title": "ngx-bootstrap",
|
||||
"url": "http://valor-software.com/ngx-bootstrap/#/"
|
||||
},
|
||||
"ab": {
|
||||
"desc": "Material Design components for Angular",
|
||||
"desc": "Componentes de Material Design para Angular",
|
||||
"logo": "",
|
||||
"title": "Angular Material",
|
||||
"url": "https://material.angular.io/"
|
||||
},
|
||||
"mcc": {
|
||||
"desc": "Material components made by the community",
|
||||
"desc": "Componentes Material fabricados por la comunidad",
|
||||
"logo": "",
|
||||
"title": "Material Community Components",
|
||||
"url": "https://github.com/tiaguinho/material-community-components"
|
||||
},
|
||||
"mosaic": {
|
||||
"desc": "Positive Technologies UI components based on Angular",
|
||||
"desc": "Positive Technologies Componentes UI basada en Angular",
|
||||
"logo": "https://i.ibb.co/fQNPgv6/logo-png-200.png",
|
||||
"title": "Mosaic - Angular UI Components",
|
||||
"title": "Mosaic - Angular Componentes UI",
|
||||
"url": "https://github.com/positive-js/mosaic"
|
||||
},
|
||||
"ngzorro": {
|
||||
"desc": "A set of enterprise-class UI components based on Ant Design and Angular",
|
||||
"title": "Ant Design of Angular (ng-zorro-antd)",
|
||||
"desc": "Un conjunto de UI de Componentes de clase empresarial basada en Ant Design y Angular",
|
||||
"title": "Ant Design de Angular (ng-zorro-antd)",
|
||||
"url": "https://ng.ant.design/docs/introduce/en"
|
||||
},
|
||||
"ngzorromobile": {
|
||||
"desc": "A set of enterprise-class mobile UI components based on Ant Design Mobile and Angular",
|
||||
"title": "Ant Design Mobile of Angular (ng-zorro-antd-mobile)",
|
||||
"title": "Ant Design Mobile de Angular (ng-zorro-antd-mobile)",
|
||||
"url": "http://ng.mobile.ant.design/#/docs/introduce/en"
|
||||
},
|
||||
"aggrid": {
|
||||
"desc": "A datagrid for Angular with enterprise style features such as sorting, filtering, custom rendering, editing, grouping, aggregation and pivoting.",
|
||||
"desc": "Una cuadrícula de datos para Angular con características de estilo empresarial como clasificación, filtrado, renderizado personalizado, edición, agrupación, agregación y pivotación.",
|
||||
"title": "ag-Grid",
|
||||
"url": "https://www.ag-grid.com/best-angular-2-data-grid/"
|
||||
},
|
||||
"angular-slickgrid": {
|
||||
"desc": "Angular-SlickGrid is a wrapper of the lightning fast & customizable SlickGrid datagrid library with Bootstrap 3,4 themes",
|
||||
"desc": "Angular-SlickGrid es un contenedor de la biblioteca de cuadrículas de datos SlickGrid, ultrarrápida y personalizable, con temas de Bootstrap 3,4",
|
||||
"title": "Angular-Slickgrid",
|
||||
"url": "https://github.com/ghiscoding/Angular-Slickgrid"
|
||||
},
|
||||
"fancygrid": {
|
||||
"desc": "Angular grid library with charts integration and server communication for Enterprise.",
|
||||
"desc": "Biblioteca de cuadrícula Angular con integración de gráficos y comunicación con el servidor para empresas.",
|
||||
"title": "FancyGrid",
|
||||
"url": "https://fancygrid.com/docs/getting-started/angular"
|
||||
},
|
||||
"ngx-smart-modal": {
|
||||
"desc": "Angular smart, light and fast modal handler to manage modals and data everywhere.",
|
||||
"desc": "Controlador modal Angular inteligente, ligero y rápido para administrar modales y datos en todas partes.",
|
||||
"title": "ngx-smart-modal",
|
||||
"url": "https://biig-io.github.io/ngx-smart-modal"
|
||||
},
|
||||
"jqwidgets": {
|
||||
"desc": "Angular UI Components including data grid, tree grid, pivot grid, scheduler, charts, editors and other multi-purpose components",
|
||||
"desc": "Interfaz de usuario de Angular Componentes que incluye cuadrícula de datos, cuadrícula de árbol, cuadrícula dinámica, programador, gráficos, editores y otros componentes multipropósito",
|
||||
"title": "jQWidgets",
|
||||
"url": "https://www.jqwidgets.com/angular/"
|
||||
},
|
||||
"amexio": {
|
||||
"desc": "Amexio is a rich set of Angular components powered by HTML5 & CSS3 for Responsive Web Design and 80+ built-in Material Design Themes. Amexio has 3 Editions, Standard, Enterprise and Creative. Std Edition consists of basic UI Components which include Grid, Tabs, Form Inputs and so on. While Enterprise Edition consists of components like Calendar, Tree Tabs, Social Media Logins (Facebook, GitHub, Twitter and so on) and Creative Edition is focused building elegant and beautiful websites. With more than 200+ components/features. All the editions are open-sourced and free, based on Apache 2 License.",
|
||||
"title": "Amexio - Angular Extensions",
|
||||
"desc": "Amexio es un extenso conjunto de componentes Angular impulsados por HTML5 y CSS3 para diseño web receptivo y más de 80 temas de diseño de materiales integrados. Amexio tiene 3 ediciones, Standard, Enterprise y Creative. Std Edition consta de una interfaz de usuario básica de Componentes que incluye cuadrícula, pestañas, entradas de formulario, etc. Mientras que Enterprise Edition consta de componentes como Calendario, pestañas de árbol, inicios de sesión en redes sociales (Facebook, GitHub, Twitter, etc.) y Creative Edition se centra en la construcción de sitios web elegantes y hermosos. Con más de 200 componentes/características. Todas las ediciones son de código abierto y gratuitas, basadas en la licencia Apache 2.",
|
||||
"title": "Amexio - Extensiones Angular",
|
||||
"url": "http://www.amexio.tech/",
|
||||
"logo": "http://www.amexio.org/amexio-logo.png"
|
||||
},
|
||||
"bm": {
|
||||
"desc": "A lightweight Material Design library for Angular, based upon Google's Material Components for the Web",
|
||||
"desc": "Una biblioteca ligera de diseño de materiales para Angular, basada en los componentes de materiales de Google para la Web",
|
||||
"logo": "https://blox.src.zone/assets/bloxmaterial.03ecfe4fa0147a781487749dc1cc4580.svg",
|
||||
"title": "Blox Material",
|
||||
"url": "https://github.com/src-zone/material"
|
||||
},
|
||||
"essentialjs2": {
|
||||
"desc": "Essential JS 2 for Angular is a collection modern TypeScript based true Angular Components. It has support for Ahead Of Time (AOT) compilation and Tree-Shaking. All the components are developed from the ground up to be lightweight, responsive, modular and touch friendly.",
|
||||
"desc": "Essential JS 2 para Angular es una colección de componentes Angular verdaderos basados en TypeScript modernos. Tiene soporte para la compilación Ahead Of Time (AOT) y Tree-Shaking. Todos los componentes se desarrollan desde cero para ser livianos, receptivos, modulares y fáciles de tocar.",
|
||||
"title": "Essential JS 2",
|
||||
"url": "https://www.syncfusion.com/products/angular-js2"
|
||||
},
|
||||
"trulyui": {
|
||||
"desc": "TrulyUI is an Angular UI Framework especially developed for Desktop Applications based on Web Components using the greatest technologies of the world.",
|
||||
"desc": "TrulyUI es un marco de interfaz de usuario Angular especialmente desarrollado para aplicaciones de escritorio basadas en componentes web que utilizan las mejores tecnologías del mundo.",
|
||||
"title": "Truly UI",
|
||||
"url": "http://truly-ui.com"
|
||||
},
|
||||
"ngsqui": {
|
||||
"desc": "Simple Quality UI (SQ-UI) is a flexible and easily customizable UI-kit, aiming to provide maximum efficiency with as little overhead as possible. Driven by the idea that it should be strictly \"for developers by developers\", every new feature release includes functionalities demanded by the developers who are using it.",
|
||||
"desc": "La interfaz de usuario de calidad simple (SQ-UI) es un kit de interfaz de usuario flexible y fácilmente personalizable, cuyo objetivo es proporcionar la máxima eficiencia con la menor sobrecarga posible. Impulsado por la idea de que debería ser estrictamente \" para desarrolladores por desarrolladores \", cada lanzamiento de nuevas funciones incluye funcionalidades exigidas por los desarrolladores que lo utilizan.",
|
||||
"logo": "https://sq-ui.github.io/ng-sq-ui/_media/sq-ui-logo.png",
|
||||
"title": "Simple Quality UI",
|
||||
"url": "https://sq-ui.github.io/ng-sq-ui/#/"
|
||||
},
|
||||
"smart": {
|
||||
"desc": "Web Components for Angular. Dependency-free Angular components for building modern and mobile-friendly web apps",
|
||||
"title": "Smart Web Components",
|
||||
"desc": "Componentes web para Angular. Componentes Angular sin dependencias para crear aplicaciones web modernas y aptas para dispositivos móviles",
|
||||
"title": "Componentes web inteligentes",
|
||||
"url": "https://www.htmlelements.com/angular/"
|
||||
},
|
||||
"AlyleUI": {
|
||||
"desc": "Minimal Design, a set of components for Angular.",
|
||||
"desc": "Minimal Design, un conjunto de componentes para Angular.",
|
||||
"title": "Alyle UI",
|
||||
"url": "https://alyle-ui.firebaseapp.com/"
|
||||
},
|
||||
"nebular": {
|
||||
"desc": "Theme System, UI Components, Auth and Security for your next Angular application.",
|
||||
"desc": "Theme System, Componentes UI, Autenticación y seguridad para su próxima aplicación Angular.",
|
||||
"title": "Nebular",
|
||||
"url": "https://akveo.github.io/nebular/"
|
||||
},
|
||||
"carbondesignsystem": {
|
||||
"desc": "An Angular implementation of the Carbon Design System for IBM.",
|
||||
"desc": "Una implementación Angular del Carbon Design System para IBM.",
|
||||
"title": "Carbon Components Angular",
|
||||
"url": "https://angular.carbondesignsystem.com/"
|
||||
},
|
||||
"jigsaw": {
|
||||
"desc": "Jigsaw provides a set of web components based on Angular. It is supporting the development of all applications of Big Data Product of ZTE (https://www.zte.com.cn).",
|
||||
"desc": "Jigsaw proporciona un conjunto de componentes web basados en Angular. Está apoyando el desarrollo de todas las aplicaciones de Big Data Producto de ZTE (https://www.zte.com.cn).",
|
||||
"title": "Awade Jigsaw (Chinese)",
|
||||
"url": "https://jigsaw-zte.gitee.io"
|
||||
}
|
||||
@ -434,295 +422,296 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Education": {
|
||||
"Educación": {
|
||||
"order": 2,
|
||||
"subCategories": {
|
||||
"Books": {
|
||||
"Libros": {
|
||||
"order": 1,
|
||||
"resources": {
|
||||
"-KLIzGEp8Mh5W-FkiQnL": {
|
||||
"desc": "Your quick, no-nonsense guide to building real-world apps with Angular",
|
||||
"title": "Learning Angular - Second Edition",
|
||||
"desc": "Tu guía rápida y sensata para crear aplicaciones del mundo real con Angular",
|
||||
"title": "Aprendiendo Angular - Segunda edición",
|
||||
"url": "https://www.packtpub.com/web-development/learning-angular-second-edition"
|
||||
},
|
||||
"3ab": {
|
||||
"desc": "More than 15 books from O'Reilly about Angular",
|
||||
"title": "O'Reilly Media",
|
||||
"desc": "Más de 15 libros de O'Reilly sobre Angular",
|
||||
"title": "Medios de comunicación O'Reilly",
|
||||
"url": "https://ssearch.oreilly.com/?q=angular"
|
||||
},
|
||||
"a5b": {
|
||||
"desc": "The in-depth, complete, and up-to-date book on Angular. Become an Angular expert today.",
|
||||
"desc": "El libro en profundidad, completo y actualizado sobre Angular. Conviértete en un experto en Angular hoy.",
|
||||
"title": "ng-book",
|
||||
"url": "https://www.ng-book.com/2/"
|
||||
},
|
||||
"a7b": {
|
||||
"desc": "This ebook will help you getting the philosophy of the framework: what comes from 1.x, what has been introduced and why",
|
||||
"title": "Becoming a Ninja with Angular",
|
||||
"desc": "Este libro electrónico te ayudará a comprender la filosofía del marco: qué proviene de 1.x, qué se ha introducido y por qué",
|
||||
"title": "Convertirse en un ninja con Angular",
|
||||
"url": "https://books.ninja-squad.com/angular"
|
||||
},
|
||||
"ab": {
|
||||
"desc": "More than 10 books from Packt Publishing about Angular",
|
||||
"desc": "Más de 10 libros de Packt Publicados sobre Angular",
|
||||
"title": "Packt Publishing",
|
||||
"url": "https://www.packtpub.com/catalogsearch/result/?q=angular"
|
||||
},
|
||||
"cnoring-rxjs-fundamentals": {
|
||||
"desc": "A free book that covers all facets of working with Rxjs from your first Observable to how to make your code run at optimal speed with Schedulers.",
|
||||
"desc": "Un libro gratuito que cubre todas las facetas del trabajo con Rxjs, desde tu primer Observable hasta cómo hacer que tu código se ejecute a una velocidad óptima con Schedulers.",
|
||||
"title": "RxJS Ultimate",
|
||||
"url": "https://chrisnoring.gitbooks.io/rxjs-5-ultimate/content/"
|
||||
},
|
||||
"vsavkin-angular-router": {
|
||||
"desc": "This book is a comprehensive guide to the Angular router written by its designer. The book explores the library in depth, including the mental model, design constraints, subtleties of the API.",
|
||||
"desc": "Este libro es una guía completa del enrutador Angular escrita por su diseñador. El libro explora la biblioteca en profundidad, incluido el modelo mental, las limitaciones de diseño y las sutilezas de la API.",
|
||||
"title": "Angular Router",
|
||||
"url": "https://leanpub.com/router"
|
||||
},
|
||||
"vsavkin-essential-angular": {
|
||||
"desc": "The book is a short, but at the same time, fairly complete overview of the key aspects of Angular written by its core contributors Victor Savkin and Jeff Cross. The book will give you a strong foundation. It will help you put all the concepts into right places. So you will get a good understanding of why the framework is the way it is.",
|
||||
"title": "Essential Angular",
|
||||
"desc": "El libro es una descripción breve, pero al mismo tiempo bastante completa, de los aspectos clave de Angular escrita por sus colaboradores principales, Victor Savkin y Jeff Cross. El libro te dará una base sólida. Te ayudará a poner todos los conceptos en los lugares correctos. De este modo, comprenderás bien por qué el marco es como es.",
|
||||
"title": "Angular Esencial",
|
||||
"url": "https://gumroad.com/l/essential_angular"
|
||||
},
|
||||
"angular-buch": {
|
||||
"desc": "The first German book about Angular. It gives you a detailed practical overview of the key concepts of the platform. In each chapter a sample application is built upon with a new Angular topic. All sources are available on GitHub.",
|
||||
"desc": "El primer libro alemán sobre Angular. Te brinda una descripción práctica detallada de los conceptos clave de la plataforma. En cada capítulo se crea una aplicación de muestra con un nuevo tema de Angular. Todas las fuentes están disponibles en GitHub.",
|
||||
"logo": "https://angular-buch.com/assets/img/brand.svg",
|
||||
"title": "Angular-Buch (German)",
|
||||
"title": "Angular-Buch (Alemán)",
|
||||
"url": "https://angular-buch.com/"
|
||||
},
|
||||
"wishtack-guide-angular": {
|
||||
"desc": "The free, open-source and up-to-date Angular guide. This pragmatic guide is focused on best practices and will drive you from scratch to cloud.",
|
||||
"desc": "La guía de Angular gratuita, de código abierto y actualizada. Esta guía pragmática se centra en las mejores prácticas y lo llevará de cero a la nube.",
|
||||
"logo": "https://raw.githubusercontent.com/wishtack/gitbook-guide-angular/master/.gitbook/assets/wishtack-logo-with-text.png",
|
||||
"title": "The Angular Guide by Wishtack (Français)",
|
||||
"title": "La guía de Angular de Wishtack (Francés)",
|
||||
"url": "https://guide-angular.wishtack.io/"
|
||||
},
|
||||
"ab5": {
|
||||
"desc": "How to build Angular applications using NGRX",
|
||||
"desc": "Cómo construir aplicaciones Angular usando NGRX",
|
||||
"logo": "",
|
||||
"title": "Architecting Angular Applications with NGRX",
|
||||
"title": "Arquitectura de aplicaciones Angular con NGRX",
|
||||
"url": "https://www.packtpub.com/web-development/architecting-angular-applications-redux"
|
||||
},
|
||||
"dwa": {
|
||||
"desc": "Practical journey with Angular framework, ES6, TypeScript, webpack and Angular CLI.",
|
||||
"title": "Developing with Angular",
|
||||
"desc": "Viaje práctico con Angular framework, ES6, TypeScript, webpack y Angular CLI.",
|
||||
"title": "Desarrollando con Angular",
|
||||
"url": "https://leanpub.com/developing-with-angular"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Online Training": {
|
||||
"Entrenamiento en linea": {
|
||||
"order": 3,
|
||||
"resources": {
|
||||
"angular-dyma": {
|
||||
"desc": "Learn Angular and all its ecosystem (Material, Flex-layout, Ngrx and more) from scratch.",
|
||||
"title": "Dyma (French)",
|
||||
"desc": "Aprende Angular y todo su ecosistema (Material, Flex-layout, Ngrx y más) desde cero.",
|
||||
"title": "Dyma (francés)",
|
||||
"url": "https://dyma.fr/angular"
|
||||
},
|
||||
"-KLIBoTWXMiBcvG0dAM6": {
|
||||
"desc": "This course introduces you to the essentials of this \"superheroic\" framework, including declarative templates, two-way data binding, and dependency injection.",
|
||||
"title": "Angular: Essential Training",
|
||||
"desc": "Este curso le presenta los conceptos básicos de este marco \"superheroico\", incluidas las plantillas declarativas, el enlace de datos bidireccional y la inyección de dependencias.",
|
||||
"title": "Angular: entrenamiento esencial",
|
||||
"url": "https://www.lynda.com/AngularJS-tutorials/Angular-2-Essential-Training/540347-2.html"
|
||||
},
|
||||
"-KLIzGq3CiFeoZUemVyE": {
|
||||
"desc": "Learn the core concepts, play with the code, become a competent Angular developer",
|
||||
"title": "Angular Concepts, Code and Collective Wisdom",
|
||||
"desc": "Aprenda los conceptos básicos, juegue con el código, conviértase en un desarrollador Angular competente",
|
||||
"title": "Conceptos Angular, código y sabiduría colectiva",
|
||||
"url": "https://www.udemy.com/angular-2-concepts-code-and-collective-wisdom/"
|
||||
},
|
||||
"-KLIzHwg-glQLXni1hvL": {
|
||||
"desc": "Spanish language Angular articles and information",
|
||||
"desc": "Artículos e información de Angular en español",
|
||||
"title": "Academia Binaria (español)",
|
||||
"url": "http://academia-binaria.com/"
|
||||
},
|
||||
"-KN3uNQvxifu26D6WKJW": {
|
||||
"category": "Education",
|
||||
"desc": "Create the future of web applications by taking Angular for a test drive.",
|
||||
"subcategory": "Online Training",
|
||||
"title": "CodeSchool: Accelerating Through Angular",
|
||||
"category": "Educación",
|
||||
"desc": "Cree el futuro de las aplicaciones web probando Angular.",
|
||||
"subcategory": "Entrenamiento en linea",
|
||||
"title": "CodeSchool: Acelerando a través de Angular",
|
||||
"url": "https://www.codeschool.com/courses/accelerating-through-angular-2"
|
||||
},
|
||||
"angular-playbook": {
|
||||
"desc": "Learn advanced Angular best practices for enterprise teams, created by Nrwl.io.",
|
||||
"desc": "Aprenda las mejores prácticas avanzadas de Angular para equipos empresariales, creadas por Nrwl.io.",
|
||||
"logo": "https://nrwl.io/assets/logo_footer_2x.png",
|
||||
"title": "Angular Enterprise Playbook",
|
||||
"title": "Libro de estrategias de Angular Enterprise",
|
||||
"url": "https://angularplaybook.com"
|
||||
},
|
||||
"a2b": {
|
||||
"desc": "Hundreds of Angular courses for all skill levels",
|
||||
"desc": "Cientos de cursos Angular para todos los niveles",
|
||||
"logo": "",
|
||||
"title": "Pluralsight",
|
||||
"url": "https://www.pluralsight.com/paths/angular"
|
||||
},
|
||||
"ab3": {
|
||||
"desc": "Angular courses hosted by Udemy",
|
||||
"desc": "Cursos de Angular alojados por Udemy",
|
||||
"logo": "",
|
||||
"title": "Udemy",
|
||||
"url": "https://www.udemy.com/courses/search/?q=angular"
|
||||
},
|
||||
"ab4": {
|
||||
"desc": "Angular Fundamentals and advanced topics focused on Redux Style Angular Applications",
|
||||
"desc": "Fundamentos de Angular y temas avanzados enfocados en Aplicaciones Angular de Estilo Redux",
|
||||
"logo": "",
|
||||
"title": "Egghead.io",
|
||||
"url": "https://egghead.io/browse/frameworks/angular"
|
||||
},
|
||||
"ab5": {
|
||||
"desc": "Build Web Apps with Angular - recorded video content",
|
||||
"desc": "Cree aplicaciones web con Angular: contenido de video grabado",
|
||||
"logo": "",
|
||||
"title": "Frontend Masters",
|
||||
"url": "https://frontendmasters.com/courses/angular-core/"
|
||||
},
|
||||
"angular-love": {
|
||||
"desc": "Polish language Angular articles and information",
|
||||
"title": "angular.love (Polski)",
|
||||
"desc": "Artículos e información de Angular en polaco",
|
||||
"title": "angular.love (Polaco)",
|
||||
"url": "http://www.angular.love/"
|
||||
},
|
||||
"learn-angular-fr": {
|
||||
"desc": "French language Angular content.",
|
||||
"title": "Learn Angular (francais)",
|
||||
|
||||
"desc": "Contenido de Angular en Lengua francesa.",
|
||||
"title": "Aprende Angular (francés)",
|
||||
"url": "http://www.learn-angular.fr/"
|
||||
},
|
||||
"upgrading-ajs": {
|
||||
"desc": "The world's most comprehensive, step-by-step course on using best practices and avoiding pitfalls while migrating from AngularJS to Angular.",
|
||||
"title": "Upgrading AngularJS",
|
||||
"desc": "El curso paso a paso más completo del mundo sobre el uso de las mejores prácticas y cómo evitar errores al migrar de AngularJS a Angular.",
|
||||
"title": "Actualización AngularJS",
|
||||
"url": "https://www.upgradingangularjs.com"
|
||||
},
|
||||
"toddmotto-ultimateangular": {
|
||||
"desc": "Online courses providing in-depth coverage of the Angular ecosystem, AngularJS, Angular and TypeScript, with functional code samples and a full-featured seed environment. Get a deep understanding of Angular and TypeScript from foundation to functional application, then move on to advanced topics with Todd Motto and collaborators.",
|
||||
"desc": "Cursos en línea que brindan una cobertura en profundidad del ecosistema Angular, AngularJS, Angular y TypeScript, con muestras de código funcional y un entorno de semillas con todas las funciones. Obtenga una comprensión profunda de Angular y TypeScript desde la base hasta la aplicación funcional, luego pase a temas avanzados con Todd Motto y sus colaboradores.",
|
||||
"title": "Ultimate Angular",
|
||||
"url": "https://ultimateangular.com/"
|
||||
},
|
||||
"willh-angular-zero": {
|
||||
"desc": "Online video course in Chinese for newbies who need to learning from the scratch in Chinese. It's covering Angular, Angular CLI, TypeScript, VSCode, and some must known knowledge of Angular development.",
|
||||
"title": "Angular in Action: Start From Scratch (正體中文)",
|
||||
"desc": "Video curso en línea en chino para principiantes que necesitan aprender en chino desde cero. Cubre Angular, Angular CLI, TypeScript, VSCode, y algunos deben tener conocimiento del desarrollo Angular.",
|
||||
"title": "Angular en acción: empezar desde cero (正體中文)",
|
||||
"url": "https://www.udemy.com/angular-zero/?couponCode=ANGULAR.IO"
|
||||
},
|
||||
"angular-firebase": {
|
||||
"desc": "Video lessons covering progressive web apps with Angular, Firebase, RxJS, and related APIs.",
|
||||
"desc": "Lecciones en video que cubren aplicaciones web progresivas con Angular, Firebase, RxJS y API relacionadas.",
|
||||
"title": "AngularFirebase.com",
|
||||
"url": "https://angularfirebase.com/"
|
||||
},
|
||||
"loiane-angulartraining": {
|
||||
"desc": "Free Angular course in Portuguese.",
|
||||
"title": "Loiane Training (Português)",
|
||||
"desc": "Curso gratuito de Angular en portugués.",
|
||||
"title": "Loiane Training (Portugués)",
|
||||
"url": "https://loiane.training/course/angular/"
|
||||
},
|
||||
"web-dev-angular": {
|
||||
"desc": "Build performant and progressive Angular applications.",
|
||||
"desc": "Cree aplicaciones Angular progresivas y de alto rendimiento.",
|
||||
"title": "web.dev/angular",
|
||||
"url": "https://web.dev/angular"
|
||||
},
|
||||
"mdb-angular-boilerplate": {
|
||||
"desc": "Angular CRUD application starter with NgRx state management, Firebase backend and installation guide.",
|
||||
"desc": "Iniciador de aplicaciones Angular CRUD con administración de estado NgRx, backend de Firebase y guía de instalación.",
|
||||
"title": "MDB Angular Boilerplate",
|
||||
"url": "https://github.com/mdbootstrap/Angular-Bootstrap-Boilerplate"
|
||||
},
|
||||
"dotnettricks": {
|
||||
"desc": "Online videos and training for Angular.",
|
||||
"desc": "Vídeos online y formación para Angular.",
|
||||
"logo": "",
|
||||
"title": "DotNetTricks",
|
||||
"url": "https://www.dotnettricks.com/courses/angular"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Workshops & Onsite Training": {
|
||||
"Talleres y formación presencial": {
|
||||
"order": 2,
|
||||
"resources": {
|
||||
"webucator": {
|
||||
"desc": "Customized in-person instructor-led Angular training for private groups and public online instructor-led Angular classes.",
|
||||
"desc": "Capacitación en Angular personalizada en persona dirigida por un instructor para grupos privados y clases Angular públicas en línea dirigidas por un instructor.",
|
||||
"title": "Webucator",
|
||||
"url": "https://www.webucator.com/webdev-training/angular-training"
|
||||
},
|
||||
"-acceleb": {
|
||||
"desc": "Customized, Instructor-Led Angular Training",
|
||||
"desc": "Entrenamiento Angular personalizado y dirigido por un instructor",
|
||||
"title": "Accelebrate",
|
||||
"url": "https://www.accelebrate.com/angular-training"
|
||||
},
|
||||
"-KLIBoFWStce29UCwkvY": {
|
||||
"desc": "Private Angular Training and Mentoring",
|
||||
"desc": "Capacitación y tutoría privada de Angular",
|
||||
"title": "Chariot Solutions",
|
||||
"url": "http://chariotsolutions.com/course/angular2-workshop-fundamentals-architecture/"
|
||||
},
|
||||
"-KLIBoN0p9be3kwC6-ga": {
|
||||
"desc": "Angular Academy is a two day hands-on public course given in-person across Canada!",
|
||||
"desc": "¡Angular Academy es un curso público práctico de dos días que se imparte en persona en todo Canadá!",
|
||||
"title": "Angular Academy (Canada)",
|
||||
"url": "http://www.angularacademy.ca"
|
||||
},
|
||||
"at": {
|
||||
"desc": "Angular Training teaches Angular on-site all over the world. Also provides consulting and mentoring.",
|
||||
"desc": "Angular Training enseña Angular in situ en todo el mundo. También brinda consultoría y tutoría.",
|
||||
"title": "Angular Training",
|
||||
"url": "http://www.angulartraining.com"
|
||||
},
|
||||
"-KLIBo_lm-WrK1Sjtt-2": {
|
||||
"desc": "Basic and Advanced training across Europe in German",
|
||||
"desc": "Formación básica y avanzada en toda Europa en alemán",
|
||||
"title": "TheCodeCampus (German)",
|
||||
"url": "https://www.thecodecampus.de/schulungen/angular"
|
||||
},
|
||||
"-KLIzFhfGKi1xttqJ7Uh": {
|
||||
"desc": "4 day in-depth Angular training in Israel",
|
||||
"desc": "Formación en Angular en profundidad de 4 días en Israel",
|
||||
"title": "ng-course (Israel)",
|
||||
"url": "http://ng-course.org/"
|
||||
},
|
||||
"-KLIzIcRoDq3TzCJWnYc": {
|
||||
"desc": "Virtual and in-person training in Canada and the US",
|
||||
"desc": "Capacitación virtual y presencial en Canadá y EE. UU.",
|
||||
"title": "Web Age Solutions",
|
||||
"url": "http://www.webagesolutions.com/courses/WA2533-angular-2-programming"
|
||||
},
|
||||
"500tech": {
|
||||
"desc": "Learn from 500Tech, an Angular consultancy in Israel. This course was built by an expert developer, who lives and breathes Angular, and has practical experience with real world large scale Angular apps.",
|
||||
"desc": "Aprenda de 500Tech, una consultora de Angular en Israel. Este curso fue creado por un desarrollador experto, que vive y respira Angular, y tiene experiencia práctica con aplicaciones Angular a gran escala del mundo real.",
|
||||
"title": "Angular Hands-on Course (Israel)",
|
||||
"url": "http://angular2.courses.500tech.com/"
|
||||
},
|
||||
"9ab": {
|
||||
"desc": "OnSite Training From the Authors of \"Become A Ninja with Angular\"",
|
||||
"desc": "Capacitación en el sitio de los autores de \"Conviértete en un ninja con Angular\"",
|
||||
"title": "Ninja Squad",
|
||||
"url": "http://ninja-squad.com/formations/formation-angular2"
|
||||
},
|
||||
"a2b": {
|
||||
"desc": "Angular Boot Camp covers introductory through advanced Angular topics. It includes extensive workshop sessions, with hands-on help from our experienced developer-trainers. We take developers or teams from the beginnings of Angular understanding through a working knowledge of all essential Angular features.",
|
||||
"desc": "Angular Boot Camp cubre temas Angular desde la introducción hasta los avanzados. Incluye extensas sesiones de talleres, con la ayuda práctica de nuestros experimentados formadores-desarrolladores. Llevamos a los desarrolladores o equipos desde los inicios de la comprensión de Angular a través de un conocimiento práctico de todas las características esenciales de Angular.",
|
||||
"logo": "https://angularbootcamp.com/images/angular-boot-camp-logo.svg",
|
||||
"title": "Angular Boot Camp",
|
||||
"url": "https://angularbootcamp.com"
|
||||
},
|
||||
"ab3": {
|
||||
"desc": "Trainings & Code Reviews. We help people to get a deep understanding of different technologies through trainings and code reviews. Our services can be arranged online, making it possible to join in from anywhere in the world, or on-site to get the best experience possible.",
|
||||
"desc": "Entrenamientos y revisiones de códigos. Ayudamos a las personas a obtener un conocimiento profundo de las diferentes tecnologías a través de capacitaciones y revisiones de código. Nuestros servicios se pueden organizar en línea, lo que hace posible unirse desde cualquier parte del mundo o en el sitio para obtener la mejor experiencia posible.",
|
||||
"logo": "",
|
||||
"title": "Thoughtram",
|
||||
"url": "http://thoughtram.io/"
|
||||
},
|
||||
"jsru": {
|
||||
"desc": "Complete Angular online course. Constantly updating. Real-time webinars with immediate feedback from the teacher.",
|
||||
"desc": "Curso completo en línea de Angular. Actualización constante. Seminarios web en tiempo real con comentarios inmediatos del profesor.",
|
||||
"logo": "https://learn.javascript.ru/img/sitetoolbar__logo_ru.svg",
|
||||
"title": "Learn Javascript (Russian)",
|
||||
"url": "https://learn.javascript.ru/courses/angular"
|
||||
},
|
||||
"zenika-angular": {
|
||||
"desc": "Angular trainings delivered by Zenika (FRANCE)",
|
||||
"title": "Angular Trainings (French)",
|
||||
"desc": "Entrenamientos en Angular impartidos por Zenika (FRANCIA)",
|
||||
"title": "Entrenamientos en Angular (francés)",
|
||||
"url": "https://training.zenika.com/fr/training/angular/description"
|
||||
},
|
||||
"formationjs": {
|
||||
"desc": "Angular onsite training in Paris (France). Monthly Angular workshops and custom onsite classes. We are focused on Angular, so we are always up to date.",
|
||||
"title": "Formation JavaScript (French)",
|
||||
"desc": "Formación en Angular presencial en París (Francia). Talleres Angular mensuales y clases presenciales personalizadas. Estamos enfocados en Angular, por lo que siempre estamos al día.",
|
||||
"title": "Formation JavaScript (Frances)",
|
||||
"url": "https://formationjavascript.com/formation-angular/"
|
||||
},
|
||||
"humancoders-angular": {
|
||||
"desc": "Angular trainings delivered by Human Coders (France)",
|
||||
"title": "Formation Angular (French)",
|
||||
"desc": "Entrenamientos en Angular impartidos por Human Coders (France)",
|
||||
"title": "Formation Angular (Frances)",
|
||||
"url": "https://www.humancoders.com/formations/angular"
|
||||
},
|
||||
"wao": {
|
||||
"desc": "Onsite Angular Training delivered by We Are One Sàrl in Switzerland",
|
||||
"desc": "Formación en Angular impartida por We Are One Sàrl en Suiza",
|
||||
"logo": "https://weareone.ch/wordpress/wao-content/uploads/2014/12/logo_200_2x.png",
|
||||
"title": "We Are One Sàrl",
|
||||
"url": "https://weareone.ch/courses/angular/"
|
||||
},
|
||||
"angular-schule": {
|
||||
"desc": "Angular onsite training and public workshops in Germany from the authors of the German Angular book. We also regularly post articles and videos on our blog (in English and German language).",
|
||||
"desc": "Talleres públicos y capacitación presencial de Angular en Alemania de los autores del libro German Angular. También publicamos regularmente artículos y videos en nuestro blog (en inglés y alemán).",
|
||||
"logo": "https://angular.schule/assets/img/brand.svg",
|
||||
"title": "Angular.Schule (German)",
|
||||
"url": "https://angular.schule/"
|
||||
},
|
||||
"strbrw": {
|
||||
"desc": "Angular and RxJS trainings, Code Reviews and consultancy. We help software engineers all over the world to create better web-applications...",
|
||||
"desc": "Entrenamientos en Angular y RxJS, Revisiones de Código y consultoría. Ayudamos a los ingenieros de software de todo el mundo a crear mejores aplicaciones web ...",
|
||||
"title": "StrongBrew",
|
||||
"url": "https://strongbrew.io/"
|
||||
},
|
||||
"angular.de": {
|
||||
"desc": "Onsite Angular Training delivered by the greatest community in the german speaking area in Germany, Austria and Switzerland. We also regularly post articles and tutorials on our blog.",
|
||||
"desc": "Capacitaciónes en Angular en el lugar impartida por la mayor comunidad en el área de habla alemana en Alemania, Austria y Suiza. También publicamos regularmente artículos y tutoriales en nuestro blog.",
|
||||
"logo": "https://angular.de/assets/img/angular-de-logo.svg",
|
||||
"title": "Angular.de (German)",
|
||||
"url": "https://angular.de/"
|
||||
|
@ -1,8 +1,8 @@
|
||||
<h1>Test Code Page</h1>
|
||||
<h1>Página de códigos de prueba </h1>
|
||||
|
||||
<h2><code-tabs></h2>
|
||||
<h2><Pestañas de código></h2>
|
||||
|
||||
<p>No linenums at code-tabs level</p>
|
||||
<p> No hay listas de linenums a nivel de etiquetas de código </p>
|
||||
<code-tabs>
|
||||
<code-pane header='TS code file' language='ts'>
|
||||
class {
|
||||
@ -26,7 +26,7 @@
|
||||
</code-tabs>
|
||||
<p></p>
|
||||
|
||||
<p>No linenums at code-tabs level; linenums=true for second HTML pane</p>
|
||||
<p>Sin linenums a nivel de etiquetas de código; linenums = verdadero para el segundo panel HTML</p>
|
||||
<code-tabs >
|
||||
<code-pane header='TS code file' language='ts'>
|
||||
class {
|
||||
@ -40,10 +40,10 @@
|
||||
|
||||
<h2><code-example></h2>
|
||||
|
||||
<p>One line.</p>
|
||||
<p>Una línea.</p>
|
||||
<code-example>const foo = 'bar'</code-example>
|
||||
|
||||
<p>Multi-line, linenums=true.</p>
|
||||
<p>Multi-línea, linenums=true.</p>
|
||||
<code-example linenums='true'>
|
||||
<hero-details <em>nghost-pmm-5>
|
||||
<h2 </em>ngcontent-pmm-5>Bah Dah Bing</h2>
|
||||
@ -53,7 +53,7 @@
|
||||
</hero-details>
|
||||
</code-example>
|
||||
|
||||
<p>Default linenums (false).</p>
|
||||
<p>linenums por defecto (false).</p>
|
||||
<code-example>
|
||||
<hero-details <em>nghost-pmm-5>
|
||||
<h2 </em>ngcontent-pmm-5>Mister Fantastic</h2>
|
||||
@ -63,7 +63,7 @@
|
||||
</hero-details>
|
||||
</code-example>
|
||||
|
||||
<p>Header on this one.</p>
|
||||
<p>Encabezado en este.</p>
|
||||
<code-example header="hero-details.component.ts (excerpt)">
|
||||
<hero-details <em>nghost-pmm-5>
|
||||
<h2 </em>ngcontent-pmm-5>Mister Fantastic</h2>
|
||||
@ -73,55 +73,55 @@
|
||||
</hero-details>
|
||||
</code-example>
|
||||
|
||||
<p>An "avoid" header on this one.</p>
|
||||
<p>Un encabezado "evitar" en este.</p>
|
||||
<code-example class="avoid" header="hero-details.component.ts (Avoid)">
|
||||
<hero-details <em>nghost-pmm-5>
|
||||
<h2 </em>ngcontent-pmm-5>Mister Fantastic</h2>
|
||||
<h2 </em>ngcontent-pmm-5>Señor fantástico</h2>
|
||||
<hero-team <em>ngcontent-pmm-5 </em>nghost-pmm-6>
|
||||
<h3 _ngcontent-pmm-6>Losing Team</h3>
|
||||
<h3 _ngcontent-pmm-6>Equipo Perdedor</h3>
|
||||
</hero-team>
|
||||
</hero-details>
|
||||
</code-example>
|
||||
|
||||
## Backticked code blocks
|
||||
## Bloques de código con tilde atrás
|
||||
|
||||
```html
|
||||
<hero-details>
|
||||
<h2>Mister Fantastic</h2>
|
||||
<h2>Señor fantástico</h2>
|
||||
<hero-team>
|
||||
<h3>Losing Team</h3>
|
||||
<h3>Equipo perdedor</h3>
|
||||
</hero-team>
|
||||
</hero-details>
|
||||
```
|
||||
|
||||
<h2><live-example></h2>
|
||||
<h2><ejemplo en vivo></h2>
|
||||
|
||||
<p>Plain live-example</p>
|
||||
Try this <live-example></live-example>.
|
||||
<p>Ejemplo simple en vivo</p>
|
||||
Prueba esto <live-example></live-example>.
|
||||
|
||||
<p>live-example with title atty</p>
|
||||
<p>ejemplo en vivo con título atty</p>
|
||||
<live-example title="Good Example"></live-example>
|
||||
|
||||
<p>live-example with title body</p>
|
||||
<live-example title="Good Example">Try this great example</live-example>
|
||||
<p>ejemplo en vivo con el cuerpo del título</p>
|
||||
<live-example title="Good Example">Prueba este gran ejemplo</live-example>
|
||||
|
||||
<p>live-example with name</p>
|
||||
<p>ejemplo en vivo con nombre</p>
|
||||
<live-example name="testy" title="Better Example"></live-example>
|
||||
|
||||
<p>live-example with spacey name and stackblitz</p>
|
||||
<p>ejemplo en vivo con nombre espacial y stackblitz</p>
|
||||
<live-example name=" testy " stackblitz="super-stackblitz"></live-example>
|
||||
|
||||
<p>live-example with name and stackblitz but no download</p>
|
||||
<p>ejemplo en vivo con nombre y stackblitz pero sin descarga</p>
|
||||
<live-example name="testy" stackblitz="super-stackblitz" noDownload></live-example>
|
||||
|
||||
<p>live-example embedded with name and stackblitz</p>
|
||||
<p>ejemplo en vivo incrustado con nombre y stackblitz</p>
|
||||
<live-example embedded name="testy" stackblitz="super-stackblitz"></live-example>
|
||||
|
||||
<p>More text follows ...</p>
|
||||
<p>Sigue más texto ...</p>
|
||||
|
||||
<p>Getting Started Widgets</p>
|
||||
<p>Widgets de introducción</p>
|
||||
|
||||
<p>Interpolation</p>
|
||||
<p>Interpolación</p>
|
||||
<aio-gs-interpolation></aio-gs-interpolation>
|
||||
|
||||
<p>Property Binding</p>
|
||||
@ -134,4 +134,4 @@ Try this <live-example></live-example>.
|
||||
<aio-gs-ng-if></aio-gs-ng-if>
|
||||
|
||||
<p>NgFor</p>
|
||||
<aio-gs-ng-for></aio-gs-ng-for>
|
||||
<aio-gs-ng-for></aio-gs-ng-for>
|
1099
aio/content/navigation.en.json
Normal file
1099
aio/content/navigation.en.json
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
375
aio/content/start/start-routing.en.md
Normal file
375
aio/content/start/start-routing.en.md
Normal file
@ -0,0 +1,375 @@
|
||||
# Try it: Manage data
|
||||
|
||||
At the end of [In-app Navigation](start/start-routing "Try it: In-app Navigation"), the online store application has a product catalog with two views: a product list and product details.
|
||||
Users can click on a product name from the list to see details in a new view, with a distinct URL, or route.
|
||||
|
||||
This page guides you through creating the shopping cart in three phases:
|
||||
|
||||
* Update the product details view to include a "Buy" button, which adds the current product to a list of products that a cart service manages.
|
||||
* Add a cart component, which displays the items in the cart.
|
||||
* Add a shipping component, which retrieves shipping prices for the items in the cart by using Angular's `HttpClient` to retrieve shipping data from a `.json` file.
|
||||
|
||||
{@a services}
|
||||
## Services
|
||||
|
||||
Services are an integral part of Angular applications. In Angular, a service is an instance of a class that you can make available to any part of your application using Angular's [dependency injection system](guide/glossary#dependency-injection "Dependency injection definition").
|
||||
|
||||
Services are the place where you share data between parts of your application. For the online store, the cart service is where you store your cart data and methods.
|
||||
|
||||
{@a create-cart-service}
|
||||
## Create the shopping cart service
|
||||
|
||||
Up to this point, users can view product information, and
|
||||
simulate sharing and being notified about product changes.
|
||||
They cannot, however, buy products.
|
||||
|
||||
In this section, you add a "Buy" button to the product
|
||||
details view and set up a cart service to store information
|
||||
about products in the cart.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
A later part of this tutorial, [Use forms for user input](start/start-forms "Try it: Forms for user input"), guides you through accessing this cart service from the view where the user checks out.
|
||||
|
||||
</div>
|
||||
|
||||
{@a generate-cart-service}
|
||||
### Define a cart service
|
||||
|
||||
1. To generate a cart service, right click on the `app` folder, choose `Angular Generator`, and choose `Service`. Name the new service `cart`.
|
||||
|
||||
<code-example header="src/app/cart.service.ts" path="getting-started/src/app/cart.service.1.ts"></code-example>
|
||||
|
||||
<div class="alert is-helpful>
|
||||
|
||||
The StackBlitz generator might provide the cart service in `app.module.ts` by default. That differs from the example, which uses a bundle-optimization technique, an `@Injectable()` decorator with the `{ providedIn: 'root' }` statement.
|
||||
For more information about services, see [Introduction to Services and Dependency Injection](guide/architecture-services "Concepts > Intro to Services and DI").
|
||||
|
||||
</div>
|
||||
|
||||
1. In the `CartService` class, define an `items` property to store the array of the current products in the cart.
|
||||
|
||||
<code-example path="getting-started/src/app/cart.service.ts" header="src/app/cart.service.ts" region="props"></code-example>
|
||||
|
||||
1. Define methods to add items to the cart, return cart items, and clear the cart items:
|
||||
|
||||
<code-example path="getting-started/src/app/cart.service.ts" header="src/app/cart.service.ts" region="methods"></code-example>
|
||||
|
||||
* The `addToCart()` method appends a product to an array of `items`.
|
||||
|
||||
* The `getItems()` method collects the items users add to the cart and returns each item with its associated quantity.
|
||||
|
||||
* The `clearCart()` method returns an empty array of items.
|
||||
|
||||
{@a product-details-use-cart-service}
|
||||
### Use the cart service
|
||||
|
||||
This section walks you through using the cart service to add a product to the cart with a "Buy" button.
|
||||
|
||||
1. Open `product-details.component.ts`.
|
||||
|
||||
1. Configure the component to use the cart service.
|
||||
|
||||
1. Import the cart service.
|
||||
|
||||
<code-example header="src/app/product-details/product-details.component.ts" path="getting-started/src/app/product-details/product-details.component.ts" region="cart-service">
|
||||
</code-example>
|
||||
|
||||
1. Inject the cart service by adding it to the `constructor()`.
|
||||
|
||||
<code-example path="getting-started/src/app/product-details/product-details.component.ts" header="src/app/product-details/product-details.component.ts" region="inject-cart-service">
|
||||
</code-example>
|
||||
|
||||
<!--
|
||||
To do: Consider defining "inject" and describing the concept of "dependency injection"
|
||||
-->
|
||||
|
||||
1. Define the `addToCart()` method, which adds the current product to the cart.
|
||||
|
||||
The `addToCart()` method does the following three things:
|
||||
* Receives the current `product`.
|
||||
* Uses the cart service's `addToCart()` method to add the product the cart.
|
||||
* Displays a message that you've added a product to the cart.
|
||||
|
||||
<code-example path="getting-started/src/app/product-details/product-details.component.ts" header="src/app/product-details/product-details.component.ts" region="add-to-cart"></code-example>
|
||||
|
||||
1. Update the product details template with a "Buy" button that adds the current product to the cart.
|
||||
|
||||
1. Open `product-details.component.html`.
|
||||
|
||||
1. Add a button with the label "Buy", and bind the `click()` event to the `addToCart()` method:
|
||||
|
||||
<code-example header="src/app/product-details/product-details.component.html" path="getting-started/src/app/product-details/product-details.component.html">
|
||||
</code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The line, `<h4>{{ product.price | currency }}</h4>` uses the `currency` pipe to transform `product.price` from a number to a currency string. A pipe is a way you can transform data in your HTML template. For more information about Angular pipes, see [Pipes](guide/pipes "Pipes").
|
||||
|
||||
</div>
|
||||
|
||||
1. To see the new "Buy" button, refresh the application and click on a product's name to display its details.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/start/product-details-buy.png' alt="Display details for selected product with a Buy button">
|
||||
</div>
|
||||
|
||||
1. Click the "Buy" button to add the product to the stored list of items in the cart and display a confirmation message.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/start/buy-alert.png' alt="Display details for selected product with a Buy button">
|
||||
</div>
|
||||
|
||||
|
||||
## Create the cart view
|
||||
|
||||
At this point, users can put items in the cart by clicking "Buy", but they can't yet see their cart.
|
||||
|
||||
Create the cart view in two steps:
|
||||
|
||||
1. Create a cart component and configure routing to the new component. At this point, the cart view has only default text.
|
||||
1. Display the cart items.
|
||||
|
||||
### Set up the component
|
||||
|
||||
To create the cart view, begin by following the same steps you did to create the product details component and configure routing for the new component.
|
||||
|
||||
1. Generate a cart component, named `cart`.
|
||||
|
||||
Reminder: In the file list, right-click the `app` folder, choose `Angular Generator` and `Component`.
|
||||
|
||||
<code-example header="src/app/cart/cart.component.ts" path="getting-started/src/app/cart/cart.component.1.ts"></code-example>
|
||||
|
||||
1. Add routing (a URL pattern) for the cart component.
|
||||
|
||||
Open `app.module.ts` and add a route for the component `CartComponent`, with a `path` of `cart`:
|
||||
|
||||
<code-example header="src/app/app.module.ts" path="getting-started/src/app/app.module.ts" region="cart-route">
|
||||
</code-example>
|
||||
|
||||
1. Update the "Checkout" button so that it routes to the `/cart` url.
|
||||
|
||||
Open `top-bar.component.html` and add a `routerLink` directive pointing to `/cart`.
|
||||
|
||||
<code-example
|
||||
header="src/app/top-bar/top-bar.component.html"
|
||||
path="getting-started/src/app/top-bar/top-bar.component.html"
|
||||
region="cart-route">
|
||||
</code-example>
|
||||
|
||||
1. To see the new cart component, click the "Checkout" button. You can see the "cart works!" default text, and the URL has the pattern `https://getting-started.stackblitz.io/cart`, where `getting-started.stackblitz.io` may be different for your StackBlitz project.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/start/cart-works.png' alt="Display cart view before customizing">
|
||||
</div>
|
||||
|
||||
### Display the cart items
|
||||
|
||||
You can use services to share data across components:
|
||||
|
||||
* The product details component already uses the cart service to add products to the cart.
|
||||
* This section shows you how to use the cart service to display the products in the cart.
|
||||
|
||||
|
||||
1. Open `cart.component.ts`.
|
||||
|
||||
1. Configure the component to use the cart service.
|
||||
|
||||
1. Import the `CartService` from the `cart.service.ts` file.
|
||||
|
||||
<code-example header="src/app/cart/cart.component.ts" path="getting-started/src/app/cart/cart.component.2.ts" region="imports">
|
||||
</code-example>
|
||||
|
||||
1. Inject the `CartService` so that the cart component can use it.
|
||||
|
||||
<code-example path="getting-started/src/app/cart/cart.component.2.ts" header="src/app/cart/cart.component.ts" region="inject-cart">
|
||||
</code-example>
|
||||
|
||||
1. Define the `items` property to store the products in the cart.
|
||||
|
||||
<code-example path="getting-started/src/app/cart/cart.component.2.ts" header="src/app/cart/cart.component.ts" region="items">
|
||||
</code-example>
|
||||
|
||||
1. Set the items using the cart service's `getItems()` method. Recall that you defined this method [when you generated `cart.service.ts`](#generate-cart-service).
|
||||
|
||||
The resulting `CartComponent` class is as follows:
|
||||
|
||||
<code-example path="getting-started/src/app/cart/cart.component.3.ts" header="src/app/cart/cart.component.ts" region="props-services">
|
||||
</code-example>
|
||||
|
||||
1. Update the template with a header, and use a `<div>` with an `*ngFor` to display each of the cart items with its name and price.
|
||||
|
||||
The resulting `CartComponent` template is as follows:
|
||||
|
||||
<code-example header="src/app/cart/cart.component.html" path="getting-started/src/app/cart/cart.component.2.html" region="prices">
|
||||
</code-example>
|
||||
|
||||
1. Test your cart component.
|
||||
|
||||
1. Click on "My Store" to go to the product list view.
|
||||
1. Click on a product name to display its details.
|
||||
1. Click "Buy" to add the product to the cart.
|
||||
1. Click "Checkout" to see the cart.
|
||||
1. To add another product, click "My Store" to return to the product list.
|
||||
|
||||
Repeat to add more items to the cart.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/start/cart-page-full.png' alt="Cart view with products added">
|
||||
</div>
|
||||
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
StackBlitz tip: Any time the preview refreshes, the cart is cleared. If you make changes to the app, the page refreshes, so you'll need to buy products again to populate the cart.
|
||||
|
||||
</div>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For more information about services, see [Introduction to Services and Dependency Injection](guide/architecture-services "Concepts > Intro to Services and DI").
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
## Retrieve shipping prices
|
||||
<!-- Accessing data with the HTTP client -->
|
||||
|
||||
Servers often return data in the form of a stream.
|
||||
Streams are useful because they make it easy to transform the returned data and make modifications to the way you request that data.
|
||||
The Angular HTTP client, `HttpClient`, is a built-in way to fetch data from external APIs and provide them to your app as a stream.
|
||||
|
||||
This section shows you how to use the HTTP client to retrieve shipping prices from an external file.
|
||||
|
||||
### Predefined shipping data
|
||||
|
||||
The application that StackBlitz generates for this guide comes with predefined shipping data in `assets/shipping.json`.
|
||||
Use this data to add shipping prices for items in the cart.
|
||||
|
||||
<code-example header="src/assets/shipping.json" path="getting-started/src/assets/shipping.json">
|
||||
</code-example>
|
||||
|
||||
|
||||
### Use `HttpClient` in the `AppModule`
|
||||
|
||||
Before you can use Angular's HTTP client, you must configure your app to use `HttpClientModule`.
|
||||
|
||||
Angular's `HttpClientModule` registers the providers your app needs to use a single instance of the `HttpClient` service throughout your app.
|
||||
|
||||
1. Open `app.module.ts`.
|
||||
|
||||
This file contains imports and functionality that is available to the entire app.
|
||||
|
||||
1. Import `HttpClientModule` from the `@angular/common/http` package at the top of the file with the other imports. As there are a number of other imports, this code snippet omits them for brevity. Be sure to leave the existing imports in place.
|
||||
|
||||
<code-example header="src/app/app.module.ts" path="getting-started/src/app/app.module.ts" region="http-client-module-import">
|
||||
</code-example>
|
||||
|
||||
1. Add `HttpClientModule` to the `AppModule` `@NgModule()` `imports` array to register Angular's `HttpClient` providers globally.
|
||||
|
||||
<code-example path="getting-started/src/app/app.module.ts" header="src/app/app.module.ts" region="http-client-module">
|
||||
</code-example>
|
||||
|
||||
### Use `HttpClient` in the cart service
|
||||
|
||||
Now that the `AppModule` imports the `HttpClientModule`, the next step is to inject the `HttpClient` service into your service so your app can fetch data and interact with external APIs and resources.
|
||||
|
||||
|
||||
1. Open `cart.service.ts`.
|
||||
|
||||
1. Import `HttpClient` from the `@angular/common/http` package.
|
||||
|
||||
<code-example header="src/app/cart.service.ts" path="getting-started/src/app/cart.service.ts" region="import-http">
|
||||
</code-example>
|
||||
|
||||
1. Inject `HttpClient` into the `CartService` constructor:
|
||||
|
||||
<code-example path="getting-started/src/app/cart.service.ts" header="src/app/cart.service.ts" region="inject-http">
|
||||
</code-example>
|
||||
|
||||
|
||||
### Define the `get()` method
|
||||
|
||||
Multiple components can leverage the same service.
|
||||
Later in this tutorial, the shipping component uses the cart service to retrieve shipping data via HTTP from the `shipping.json` file.
|
||||
First, define a `get()` method.
|
||||
|
||||
1. Continue working in `cart.service.ts`.
|
||||
|
||||
1. Below the `clearCart()` method, define a new `getShippingPrices()` method that uses the `HttpClient` `get()` method to retrieve the shipping data.
|
||||
|
||||
<code-example header="src/app/cart.service.ts" path="getting-started/src/app/cart.service.ts" region="get-shipping"></code-example>
|
||||
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For more information about Angular's `HttpClient`, see the [Client-Server Interaction](guide/http "Server interaction through HTTP") guide.
|
||||
|
||||
</div>
|
||||
|
||||
## Define the shipping view
|
||||
|
||||
Now that your app can retrieve shipping data, create a shipping component and template.
|
||||
|
||||
1. Generate a new component named `shipping`.
|
||||
|
||||
Reminder: In the file list, right-click the `app` folder, choose `Angular Generator` and `Component`.
|
||||
|
||||
<code-example header="src/app/shipping/shipping.component.ts" path="getting-started/src/app/shipping/shipping.component.1.ts"></code-example>
|
||||
|
||||
1. In `app.module.ts`, add a route for shipping. Specify a `path` of `shipping` and a component of `ShippingComponent`.
|
||||
|
||||
<code-example header="src/app/app.module.ts" path="getting-started/src/app/app.module.ts" region="shipping-route"></code-example>
|
||||
|
||||
There's no link to the new shipping component yet, but you can see its template in the preview pane by entering the URL its route specifies. The URL has the pattern: `https://getting-started.stackblitz.io/shipping` where the `getting-started.stackblitz.io` part may be different for your StackBlitz project.
|
||||
|
||||
1. Modify the shipping component so that it uses the cart service to retrieve shipping data via HTTP from the `shipping.json` file.
|
||||
|
||||
1. Import the cart service.
|
||||
|
||||
<code-example header="src/app/shipping/shipping.component.ts" path="getting-started/src/app/shipping/shipping.component.ts" region="imports"></code-example>
|
||||
|
||||
1. Define a `shippingCosts` property.
|
||||
|
||||
<code-example path="getting-started/src/app/shipping/shipping.component.ts" header="src/app/shipping/shipping.component.ts" region="props"></code-example>
|
||||
|
||||
1. Inject the cart service in the `ShippingComponent` constructor:
|
||||
|
||||
<code-example path="getting-started/src/app/shipping/shipping.component.ts" header="src/app/shipping/shipping.component.ts" region="inject-cart-service"></code-example>
|
||||
|
||||
1. Set the `shippingCosts` property using the `getShippingPrices()` method from the cart service.
|
||||
|
||||
<code-example path="getting-started/src/app/shipping/shipping.component.ts" header="src/app/shipping/shipping.component.ts" region="ctor"></code-example>
|
||||
|
||||
1. Update the shipping component's template to display the shipping types and prices using the `async` pipe:
|
||||
|
||||
<code-example header="src/app/shipping/shipping.component.html" path="getting-started/src/app/shipping/shipping.component.html"></code-example>
|
||||
|
||||
The `async` pipe returns the latest value from a stream of data and continues to do so for the life of a given component. When Angular destroys that component, the `async` pipe automatically stops. For detailed information about the `async` pipe, see the [AsyncPipe API documentation](/api/common/AsyncPipe).
|
||||
|
||||
1. Add a link from the cart view to the shipping view:
|
||||
|
||||
<code-example header="src/app/cart/cart.component.html" path="getting-started/src/app/cart/cart.component.2.html"></code-example>
|
||||
|
||||
1. Test your shipping prices feature:
|
||||
|
||||
Click the "Checkout" button to see the updated cart. Remember that changing the app causes the preview to refresh, which empties the cart.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/start/cart-empty-with-shipping-prices.png' alt="Cart with link to shipping prices">
|
||||
</div>
|
||||
|
||||
Click on the link to navigate to the shipping prices.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src='generated/images/guide/start/shipping-prices.png' alt="Display shipping prices">
|
||||
</div>
|
||||
|
||||
|
||||
## Next steps
|
||||
|
||||
Congratulations! You have an online store application with a product catalog and shopping cart. You can also look up and display shipping prices.
|
||||
|
||||
To continue exploring Angular, choose either of the following options:
|
||||
* [Continue to the "Forms" section](start/start-forms "Try it: Forms for User Input") to finish the app by adding the shopping cart view and a checkout form.
|
||||
* [Skip ahead to the "Deployment" section](start/start-deployment "Try it: Deployment") to move to local development, or deploy your app to Firebase or your own server.
|
@ -1,113 +1,106 @@
|
||||
# In-app navigation
|
||||
# Navegación en la aplicación
|
||||
|
||||
At the end of [part 1](start "Get started with a basic Angular app"), the online store application has a basic product catalog.
|
||||
The app doesn't have any variable states or navigation.
|
||||
There is one URL, and that URL always displays the "My Store" page with a list of products and their descriptions.
|
||||
Al final de la [parte 1] (start "Empieza con una aplicación Angular básica"), la aplicación de la tienda en línea tiene un catálogo básico de productos. La aplicación no tiene ningun estado de variable o navegación. Hay una URL, y esa URL siempre muestra la pagina "Mi Tienda" con una lista de productos y sus descripciones.
|
||||
|
||||
This guide shows you how to use Angular [routing](guide/glossary#router "Router definition") to give the user in-app navigation. In a single-page app, instead of loading new pages, you show different components and data to the user based on where the user is in the application.
|
||||
Esta guía te muestra cómo usar Angular [Routing](guide/glossary#router "Definición de Router") para brindarle al usuario navegación dentro de la aplicación. En una aplicación de una sola página, en lugar de cargar nuevas páginas, muestras diferentes componentes y datos al usuario en función de dónde se encuentra el usuario en la aplicación.
|
||||
|
||||
The router lets you display full product details in separate [views](guide/glossary#view "View definition"), each with its own URL. Routing enables navigation from one view to the next (within the same page) as users perform tasks such as the following:
|
||||
El router te permite mostrar los detalles completos del producto en [vistas](guide/glossary#view "Definición de vista") separadas, cada una con su propia URL. El router habilita la navegación de una vista a la siguiente (dentro de la misma página) cuando los usuarios realizan tareas como las siguientes:
|
||||
|
||||
* Entering a URL in the address bar to navigate to a corresponding view.
|
||||
* Clicking links on the page to navigate to a new view.
|
||||
* Clicking the browser's back and forward buttons to navigate backward and forward through the browser history.
|
||||
* Ingresando una URL en la barra de direcciones para navegar a la vista correspondiente.
|
||||
* Haciendo clic en los enlaces de la página para navegar a una nueva vista.
|
||||
* Haciendo clic en los botones de adelante y atrás del navegador para navegar hacia atrás y hacia adelante a través del historial del navegador.
|
||||
|
||||
## Registering a route
|
||||
## Registro de una ruta
|
||||
|
||||
The app is already set up to use the Angular `Router` and to use routing to navigate to the product list component you modified earlier. This section shows you how to define a route to show individual product details.
|
||||
La aplicación ya esta configurada para usar el Angular `Router` y usar el Routing para navegar al componente de la lista de productos que modificaste anteriormente. Esta sección te muestra cómo definir una ruta para mostrar los detalles de productos individualmente.
|
||||
|
||||
1. Generate a new component for product details. Give the component the name `product-details`.
|
||||
1. Genera un nuevo componente para los detalles del producto. Asigna al componente el nombre `product-details`.
|
||||
|
||||
Reminder: In the file list, right-click the `app` folder, choose `Angular Generator` and `Component`.
|
||||
|
||||
1. In `app.module.ts`, add a route for product details, with a `path` of `products/:productId` and `ProductDetailsComponent` for the `component`.
|
||||
Recuerda: En la lista de archivos, haz clic con el botón derecho en la carpeta `app`, selecciona `Angular Generator` y `Component`.
|
||||
|
||||
2. En `app.module.ts`, agrega una ruta para los detalles del producto, con un `path` de `products/:productId` y `ProductDetailsComponent` para el `component`.
|
||||
|
||||
<code-example header="src/app/app.module.ts" path="getting-started/src/app/app.module.ts" region="product-details-route">
|
||||
</code-example>
|
||||
|
||||
Una ruta asocia una o más URL con un componente.
|
||||
|
||||
3. La directiva configura la plantilla del componente para definir cómo el usuario navega a la ruta o URL. Cuando el usuario hace clic en el nombre de un producto, la aplicación muestra los detalles de ese producto.
|
||||
|
||||
A route associates one or more URL paths with a component.
|
||||
1. Abre `product-list.component.html`.
|
||||
|
||||
1. The directive configures the component template to define how the user navigates to the route or URL. When the user clicks a product name, the app displays the details for that product.
|
||||
|
||||
1. Open `product-list.component.html`.
|
||||
|
||||
1. Update the `*ngFor` directive to assign each index in the `products` array to the `productId` variable when iterating over the list.
|
||||
|
||||
1. Modify the product name anchor to include a `routerLink`.
|
||||
1. Actualiza la directiva `*ngFor` para asignar cada índice en la matriz `products` a la variable `productId` cuando se itera sobre la lista.
|
||||
|
||||
1. Modifica el ancla del nombre del producto para incluir un `routerLink`.
|
||||
|
||||
<code-example header="src/app/product-list/product-list.component.html" path="getting-started/src/app/product-list/product-list.component.html" region="router-link">
|
||||
</code-example>
|
||||
|
||||
La directiva RouterLink le da al Router el control sobre el elemento de anclaje. En este caso, la ruta, o URL, contiene un segmento fijo, `/products`, mientras que el segmento final es variable, insertando la propiedad id del producto actual. Por ejemplo, la URL de un producto con un `id` de 1 será similar a `https://getting-started-myfork.stackblitz.io/products/1`.
|
||||
|
||||
4. Prueba el Router haciendo clic en el nombre de un producto. La aplicación muestra el componente de detalles del producto, que actualmente siempre dice "product-details works!"
|
||||
|
||||
The RouterLink directive gives the router control over the anchor element. In this case, the route, or URL, contains one fixed segment, `/products`, while the final segment is variable, inserting the id property of the current product. For example, the URL for a product with an `id` of 1 will be similar to `https://getting-started-myfork.stackblitz.io/products/1`.
|
||||
|
||||
1. Test the router by clicking a product name. The app displays the product details component, which currently always says "product-details works!"
|
||||
|
||||
Notice that the URL in the preview window changes. The final segment is `products/#` where `#` is the number of the route you clicked.
|
||||
Observa que cambia la URL en la ventana de vista previa. El segmento final es "products/#" donde "#" es el número de la ruta en la que hizo clic.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/start/product-details-works.png" alt="Product details view with updated URL">
|
||||
<img src="generated/images/guide/start/product-details-works.png" alt="Vista de detalles del producto con URL actualizada">
|
||||
</div>
|
||||
|
||||
## Utilizar información de la ruta
|
||||
|
||||
El componente de detalles del producto maneja la visualización de cada producto. El Angular Router muestra los componentes basados en la URL del navegador y sus rutas definidas. Esta sección te muestra cómo usar el Angular Router para combinar los datos de los `productos` y la información de la ruta para mostrar los detalles específicos de cada producto.
|
||||
|
||||
1. Abre `product-details.component.ts`
|
||||
|
||||
## Using route information
|
||||
|
||||
The product details component handles the display of each product. The Angular Router displays components based on the browser's URL and your defined routes. This section shows you how to use the Angular Router to combine the `products` data and route information to display the specific details for each product.
|
||||
|
||||
1. Open `product-details.component.ts`
|
||||
|
||||
1. Arrange to use product data from an external file.
|
||||
|
||||
1. Import `ActivatedRoute` from the `@angular/router` package, and the `products` array from `../products`.
|
||||
2. Organiza el uso de datos de productos desde un archivo externo.
|
||||
|
||||
1. Importa `ActivatedRoute` del paquete `@angular/router` y la matriz `products` de `../products`.
|
||||
|
||||
<code-example header="src/app/product-details/product-details.component.ts" path="getting-started/src/app/product-details/product-details.component.1.ts" region="imports">
|
||||
</code-example>
|
||||
|
||||
1. Define the `product` property and inject the `ActivatedRoute` into the constructor by adding it as an argument within the constructor's parentheses.
|
||||
|
||||
1. Define la propiedad `product` e inyecta el `ActivatedRoute` en el constructor agregándolo como un argumento dentro de los paréntesis del constructor.
|
||||
|
||||
<code-example header="src/app/product-details/product-details.component.ts" path="getting-started/src/app/product-details/product-details.component.1.ts" region="props-methods">
|
||||
</code-example>
|
||||
|
||||
El `ActivatedRoute` es específico para cada componente enrutado que carga el Angular Router. Contiene información sobre la
|
||||
ruta, sus parámetros y datos adicionales asociados con la ruta.
|
||||
|
||||
The `ActivatedRoute` is specific to each routed component that the Angular Router loads. It contains information about the
|
||||
route, its parameters, and additional data associated with the route.
|
||||
|
||||
By injecting the `ActivatedRoute`, you are configuring the component to use a *service*. The [Managing Data](start/start-data "Try it: Managing Data") page covers services in more detail.
|
||||
|
||||
|
||||
1. In the `ngOnInit()` method, subscribe to route parameters and fetch the product based on the `productId`.
|
||||
Inyectando el `ActivatedRoute`, estás configurando el componente para usar un *servicio*. La página [Manejo de Datos] (start/start-data "Pruébalo: Manejo de Datos") cubre los servicios con más detalle.
|
||||
|
||||
|
||||
3. En el método `ngOnInit()`, suscríbete a los parámetros de ruta y obtén el producto basándote en el `productId`.
|
||||
|
||||
<code-example path="getting-started/src/app/product-details/product-details.component.1.ts" header="src/app/product-details/product-details.component.ts" region="get-product">
|
||||
</code-example>
|
||||
|
||||
The route parameters correspond to the path variables you define in the route. The URL that matches the route provides the `productId`. Angular uses the `productId` to display the details for each unique product.
|
||||
|
||||
1. Update the template to display product details information inside an `*ngIf`.
|
||||
|
||||
Los parámetros de la ruta corresponden a las variables de ruta (path) que se define en la ruta. La URL que coincide con la ruta proporciona el `productId`. Angular usa el `productId` para mostrar los detalles de cada producto único.
|
||||
|
||||
4. Actualiza la plantilla para mostrar la información de detalle del producto dentro de un `*ngIf`.
|
||||
|
||||
<code-example header="src/app/product-details/product-details.component.html" path="getting-started/src/app/product-details/product-details.component.html" region="details">
|
||||
</code-example>
|
||||
|
||||
Now, when users click on a name in the product list, the router navigates them to the distinct URL for the product, swaps out the product list component for the product details component, and displays the product details.
|
||||
Ahora, cuando los usuarios hacen clic en un nombre en la lista de productos, el router los dirige a la URL distinta del producto, cambia el componente de la lista de productos por el componente de detalles del producto y muestra los detalles del producto.
|
||||
|
||||
<div class="lightbox">
|
||||
<img src="generated/images/guide/start/product-details-routed.png" alt="Product details page with updated URL and full details displayed">
|
||||
<img src="generated/images/guide/start/product-details-routed.png" alt="Página de detalles del producto con URL actualizada y detalles completos mostrados">
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For more information about the Angular Router, see [Routing & Navigation](guide/router "Routing & Navigation guide").
|
||||
Para obtener más información sobre el Angular Router, consulta [Enrutamiento y Navegación] (guide/router "Guía de Enrutamiento y Navegación").
|
||||
|
||||
</div>
|
||||
|
||||
## Próximos pasos
|
||||
|
||||
## Next steps
|
||||
¡Felicidades! Has integrado el enrutamiento en tu tienda en linea.
|
||||
|
||||
Congratulations! You have integrated routing into your online store.
|
||||
* Los productos están vinculados desde la vista de lista de productos a productos individuales.
|
||||
* Los usuarios pueden hacer clic en el nombre de un producto de la lista para ver los detalles en una nueva vista, con una URL / ruta distinta.
|
||||
|
||||
* Products are linked from the product list view to individual products.
|
||||
* Users can click on a product name from the list to see details in a new view, with a distinct URL/route.
|
||||
|
||||
To continue exploring Angular, choose either of the following options:
|
||||
* [Continue to the "Managing Data" section](start/start-data "Try it: Managing Data") to add a shopping cart feature, use a service to manage the cart data and use HTTP to retrieve external data for shipping prices.
|
||||
* [Skip ahead to the Deployment section](start/start-deployment "Try it: Deployment") to deploy your app to Firebase or move to local development.
|
||||
Para continuar explorando Angular, elige cualquiera de las siguientes opciones:
|
||||
* [Continuar con la sección "Manejo de Datos"] (start/start-data "Pruébalo: Manejo de datos") para agregar una función de carrito de compras, usa un servicio para administrar los datos del carrito y usa HTTP para recuperar datos externos para los precios del envío.
|
||||
* [Ir a la sección Despliegue] (start/start-deployment "Pruébalo: Despliegue") para implementar su aplicación en Firebase o pasar al desarrollo local.
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user